【问题标题】:Query XML Linq in C#在 C# 中查询 XML Linq
【发布时间】:2017-01-26 08:44:55
【问题描述】:

我想使用 C# 从 XML(也有一个 xsd 文件)中检索数据。我的代码有什么问题: 我的 Xml 文件看起来像这样。

<Model_1 xmlns="http://www.3ds.com/xsd/3DXML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.3ds.com/xsd/3DXML ./3DXML.xsd">
    <Header>
        <item></item>
        <item1></item1>
        <item2></item2>
    </Header>
    <Product>
        <otheritem></otheritem>
        <otheritem1></otheritem1>
        <otheritem2></otheritem2>
    </Product>
    <Books>
        <otheritem></otheritem>
        <otheritem1></otheritem1>
        <otheritem2></otheritem2>
    </Books>
</Model_1>

...c#

     XDocument xdoc = Document.Load("document.xml")                                                           var items = from item in xdoc.Descendants("Header")
                            select new
                            {
                                _Item= item.Element("Item").Value,
                                _Item1= item.Element("Item1").Value,
                                _Item2= item.Element("Item2").Value,         
                            };

                foreach (var item in items)
                {
                    Item= item._Item;
                    Item1 = item._Item1;
                    Item2 = item.Item2;
                }
 Console.WriteLine("show me :" + Item+ " + " + Item1 + " + " + Item2);

如何仅从 Header 而不是 Product 或 Books 中提取项目?

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

    你需要使用命名空间:

    var ns = xdoc.Root.GetDefaultNamespace();
    var header = xdoc.Root.Element(ns + "Header");
    

    还请记住 - 您的 xml 中有小写的 item,而不是 Item

    Item = (string)header?.Element(ns + "item");
    Item1 = (string)header?.Element(ns + "item1");
    Item2 = (string)header?.Element(ns + "item2");
    

    【讨论】:

    • @maki 复制了您的 xml 并成功解析。确保您使用的 xml 与您在问题中提供的相同
    • 非常感谢。现在可以了,这是我的错。
    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多