简体   繁体   English

Linq XML属性查询

[英]Linq query of XML attributes

So I'm trying to write a simple query that grabs all of a certain attribute from an XML file, but nothing seems to work. 因此,我正在尝试编写一个简单的查询,该查询从XML文件中获取所有特定属性,但是似乎没有任何效果。 I've been able to do this with several other XML's but for some reason the one I'm working with here just won't cooperate. 我已经可以使用其他几种XML来做到这一点,但是由于某种原因,我在这里使用的XML无法配合。 Any suggestions or advice would be hugely appreciated. 任何建议或意见将不胜感激。

Here's what the XML looks like. 这就是XML的样子。

<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>

Here's my C# code: 这是我的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);

The reason is that your XML has default namespace declared at the root element : 原因是您的XML在根元素上声明了默认名称空间:

xmlns="Name"

XML elements inherit ancestor default namespace by default, unless otherwise specified (fe by using explicit prefix that point to different namespace URI). 除非另外指定,否则XML元素默认情况下继承祖先的默认名称空间(例如,使用指向不同名称空间URI的显式前缀)。 You can use XNamespace + element's local name to point to element in namespace : 您可以使用XNamespace +元素的本地名称指向命名空间中的element:

XNamespace ns = "Name";
IEnumerable<string> names =
            from c in customers.Descendants(ns+"Box").Attributes("name")
            select c.Value;

Your document has a default namespace of "Name". 您的文档的默认名称空间为“名称”。 You need to reference the namespace when selecting a node like so: 选择像这样的节点时,您需要引用名称空间:

    IEnumerable<string> names =
        from c in customers.Descendants(XName.Get("Box", "Name")).Attributes("name")
        select c.Value;

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

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