在 C# 中查询 XML Linq

Query XML Linq in C#

我想使用 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);

如何只从页眉中提取项目而不是产品或书籍?

您需要使用命名空间:

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");