Sunday, 17 August 2014

Use LINQ XML with a namespace as attribute



I am trying to find nodes in an XML document like this:



<?xml version="1.0"?>
<TrainingCenterDatabase xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY" xmlns="http://ift.tt/VxNYPL">
<Activities>
<Activity Sport="CyclingTransport">
<Id>2014-07-08T15:28:14Z</Id>
</Activity>
</Activities>
</TrainingCenterDatabase>


I aim to extract the node value 'Id' with code like this:



XDocument doc = XDocument.Load(filePath);
List<string> urlList = doc.Root.Descendants("Id")
.Select(x => (string)x)
.ToList();
Console.WriteLine(urlList.Count);


However the count is 0, where I expect 1.


After some debugging and editing the XML I noticed that if I change the TrainingCenterDatabase node and remove the attributes to this:



<TrainingCenterDatabase>


Then the result is a count of 1 as expected.


So my question is how do I take into account the namespaces so that I can get the value when the TrainingCenterDatabase node has these attributes?


No comments:

Post a Comment