Reputation: 72
While parsing xml by linq to xml, I came across a strange behaviour (atleast to me). Below is the first xml I parsed
`<?xml version="1.0" encoding="UTF-8"?>
<TestRun>
<UnitTestResult testName = "Arun" outcome = "i">
</UnitTestResult>
<UnitTestResult testName = "Arun1" outcome = "i">
</UnitTestResult>
</TestRun>`
My Code looks like
XDocument doc = XDocument.Parse(fileContents);
var result = doc.Descendants("UnitTestResult");
The above works fine. But If my root node contain attributes the same code is not working. What could be the reason. XML sample below
<?xml version="1.0" encoding="UTF-8"?>
<TestRun id="7903b4ff-8706-4379-b9e8-567034b70abb" name="inaambika@INBELW013312A 2016-02-26 16:55:14" runUser="STC\inaambika" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<UnitTestResult testName = "Arun" outcome = "i">
</UnitTestResult>
<UnitTestResult testName = "Arun1" outcome = "i">
</UnitTestResult>
</TestRun>
XDocument doc = XDocument.Parse(fileContents);
var result = doc.Descendants("UnitTestResult");
Upvotes: 0
Views: 77
Reputation: 89285
This one below is not ordinary attribute, it is default namespace declaration :
xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"
Having default namespace declared at the root element level, the root element and all descendant elements without prefix (in this case it means all elements in the posted XML) are in that namespace.
You can use XNamespace
+ element-local-name to reference element in namespace :
XDocument doc = XDocument.Parse(fileContents);
XNamespace d = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"
var result = doc.Descendants(d+"UnitTestResult");
Upvotes: 1