Sam
Sam

Reputation: 446

Parsing XML in C# to retrieve values

I need to parse and read values from the following XML format:

<?xml version="1.0"?>
<Patients xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Person xmlns="http://ehr.org/VM/" NationalCode="1234" LastName="Morgan" FirstName="Alen">
    </Person>
</Patients>

And I'm trying to read name of patients and birthday details using following code but for some reason xml.SelectNodes("/Patients/Person") is null, any idea how can I read the values from the xml?

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); 

XmlNodeList xnList = xml.SelectNodes("/Patients/Person");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName  = xn["LastName"].InnerText;
}

Upvotes: 2

Views: 73

Answers (1)

John Wright
John Wright

Reputation: 4607

There are a couple of things you need to fix.

First, the Person type in your XML is scoped to a namespace, so you need to include that namespace (via a XmlNamespaceManager) when you search for that node.

To do this, you add the namespace via the AddNamespace method and give it an alias and the namespace you want to use in your search. In my example, I used the alias ehr.

Then, provide the namespace manager into .SelectNodes() and prefix the "Person" in your search string with your alias (ex: /Patients/ehr:Person)

Second, the FirstName and LastName items are attributes, which you must access via the Attributes property. Just using xn["FirstName"] will look for a child node with that name.

Here's the working code:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("ehr", "http://ehr.org/VM/");

XmlNodeList xnList = xml.SelectNodes("/Patients/ehr:Person", nsmgr);
foreach (XmlNode xn in xnList)
{

     string firstName = xn.Attributes["FirstName"].Value;
     string lastName = xn.Attributes["LastName"].Value;
}

Upvotes: 2

Related Questions