WT86 WT86 - 1 month ago 5x
C# Question

Extracting XML tags values

I have a list of XML files that I need to extract 3 values from each file.
The XML looks somewhat like :

<ClinicalDocument xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" moodCode="EVN" xmlns="urn:hl7-org:v3">

<birthTime value="19480503" />

I'm trying to extract given name, family name and birth time.

Initially I'm trying to print out the values using:

XmlDocument doc2 = new XmlDocument();

XmlElement root = doc2.DocumentElement;
XmlNodeList list = root.GetElementsByTagName("name");
for (int i = 0; i < list.Count; i++)

I'm not getting any value printed, but when I debug and check the inner values of "list" I can see what I need from that tag.

How can I extract the needed information?


Your code and all other answers ignore the default namespace xmlns="urn:hl7-org:v3"

I find Linq2Xml easier to use, so I'll post an answer using it..

var xDoc = XDocument.Load(filename);

var @namespace = "urn:hl7-org:v3";

XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);
namespaceManager.AddNamespace("ns", @namespace);
XNamespace ns = @namespace;

var names = xDoc.XPathSelectElements("//ns:patient/ns:name", namespaceManager).ToList();

var list = names.Select(p => new
                     Given = string.Join(", ", p.Elements(ns + "given").Select(x => (string)x)),
                     Family = (string)p.Element(ns + "family"),
                     BirthTime = new DateTime(1970,1,1).AddSeconds( (int)p.Parent.Element(ns + "birthTime").Attribute("value"))