简体   繁体   English

xml Linq to XML的根节点中的属性值

[英]Attribute value in root node of xml Linq to XML

While parsing xml by linq to xml, I came across a strange behaviour (atleast to me). 当通过linq将xml解析为xml时,我遇到了一种奇怪的行为(至少对我而言)。 Below is the first xml I parsed 以下是我解析的第一个xml

`<?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示例

<?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");

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. 在根元素级别声明了默认名称空间后 ,根元素和所有没有前缀的后代元素(在这种情况下,这意味着发布的XML中的所有元素)都在该名称空间中。

You can use XNamespace + element-local-name to reference element in namespace : 您可以使用XNamespace + element-local-name引用命名空间中的元素:

XDocument doc = XDocument.Parse(fileContents);
XNamespace d = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"
var result = doc.Descendants(d+"UnitTestResult");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM