【问题标题】:Linq query of XML attributesXML属性的Linq查询
【发布时间】:2015-07-16 12:16:26
【问题描述】:

所以我正在尝试编写一个简单的查询,从 XML 文件中获取所有特定属性,但似乎没有任何效果。我已经能够使用其他几个 XML 来做到这一点,但由于某种原因,我在这里使用的那个不会合作。任何建议或意见将不胜感激。

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

这是我的 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);

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    原因是您的 XML 在根元素中声明了默认命名空间:

    xmlns="Name"
    

    XML 元素默认继承祖先默认命名空间,除非另有说明(例如,使用指向不同命名空间 URI 的显式前缀)。您可以使用 XNamespace + 元素的本地名称 来指向命名空间中的元素:

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

    【讨论】:

      【解决方案2】:

      您的文档有一个默认命名空间“名称”。选择节点时需要引用命名空间,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多