Search code examples
c#xmldomxmlnodelist

Cannot find a way to get a child node from an XMLNodeList by text


This is killing me, I have an XMLDocument and I need to be able to get the text value of certain nodes out but everything I try fails. Given the below XML document, I need to get things like the ID of the patient, Last Name, etc.

<Message xmlns="http://" version="010" release="006">
<Header>
    <To Qualifier="C">1306841101</To>
    <From Qualifier="P">8899922</From>
</Header>
<Body>
    <RxFill>
        <Patient>
            <Identification>
      <ID>193306093523</ID>
      <ID3>111223333</ID3>
            </Identification>
            <Name>
                <LastName>Smith</LastName>
                <FirstName>Jane</FirstName>
            </Name>
        </Patient>
    </RxFill>
</Body>

I can get the actual NodeList of 'Patient' like so:

XmlNode root = oDoc.DocumentElement; 
oDoc.GetElementsByTagName("Patient")

but then I am stuck, if I then try to get a child node, the xpath never finds them.

for example:

oDoc.GetElementsByTagName("Patient")[0].SelectSingleNode("Identification")

comes up null even though I can see in the debugger that "Identification" is the FirstChild. I have added slash(es) as well: "//Identification" and no joy.

I can, however, get to it from the document:

oDoc.GetElementsByTagName("Identification")

but that won't work because I may have other tags in the document like that; I only want the Identification tag that belongs to the Patient.

I have tried looping through all the children to find them but that seems very inefficient.

Any ideas?


Solution

  • You should include the namespace in the XPath. You can do this using an XmlNamespaceManager:

    XmlNode root = oDoc.DocumentElement;
    XmlNode patient = oDoc.GetElementsByTagName("Patient")[0];
    
    XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
    nsm.AddNamespace("ns", "http://");
    
    XmlNode identification = patient.SelectSingleNode("ns:Identification", nsm);
    string id = identification.SelectSingleNode("ns:ID", nsm).InnerText;