简体   繁体   中英

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. 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. Any suggestions or advice would be hugely appreciated.

Here's what the XML looks like.

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

        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 :

xmlns="Name"

XML elements inherit ancestor default namespace by default, unless otherwise specified (fe by using explicit prefix that point to different namespace URI). You can use XNamespace + element's local name to point to element in namespace :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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