C# XML属性的Linq查询
因此,我试图编写一个简单的查询,从XML文件中获取所有特定属性,但似乎什么都不起作用。我已经能够用其他几个XML来实现这一点,但由于某种原因,我在这里使用的XML无法配合。如有任何建议,我们将不胜感激 下面是XML的样子C# XML属性的Linq查询,c#,xml,linq,C#,Xml,Linq,因此,我试图编写一个简单的查询,从XML文件中获取所有特定属性,但似乎什么都不起作用。我已经能够用其他几个XML来实现这一点,但由于某种原因,我在这里使用的XML无法配合。如有任何建议,我们将不胜感激 下面是XML的样子 <Doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Name" xsi:schemaLocation="[there's a link here]" Name="Name"> <W
<Doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="Name" xsi:schemaLocation="[there's a link here]" Name="Name">
<Wrapper>
<Box_Collection>
<Box name="Test A" test="Test B"/>
<Box name="Test C" test="Test D"/>
<Box name="Test E" test="Test F"/>
</Box_Collection>
</Wrapper>
</Doc>
这是我的C代码:
XDocument customers = XDocument.Load(@"C:\Users\folder\file.xml");
IEnumerable<string> names =
from c in customers.Descendants("Box").Attributes("name")
select c.Value;
string nameList = "Names:";
foreach (string c in names)
{
namer += " " + c;
}
textBox.AppendText(nameList);
您的文档具有默认名称空间Name。选择节点时需要引用命名空间,如下所示:
IEnumerable<string> names =
from c in customers.Descendants(XName.Get("Box", "Name")).Attributes("name")
select c.Value;
原因是XML在根元素处声明了默认命名空间:
xmlns="Name"
XML元素默认继承祖先默认名称空间,除非通过使用指向不同名称空间URI的显式前缀来指定f.e。您可以使用XNamespace+元素的本地名称指向命名空间中的元素:
XNamespace ns = "Name";
IEnumerable<string> names =
from c in customers.Descendants(ns+"Box").Attributes("name")
select c.Value;