【问题标题】:Getting XML atttributes that are deep in the structure using .net core使用 .net core 获取结构深处的 XML 属性
【发布时间】:2021-01-15 11:55:51
【问题描述】:

我有一个类似这样的 xml 结构:

<?xml version="1.0" encoding="utf-8"?>
<!--The structure-->
<myXMLRoot>
    <tree>
        <category title="Title A">Hi</category>
    </tree>
    <tree>
        <category title="Title B">Text</category>
    </tree>
</myXMLRoot>

如果我知道上面的结构,有什么方法可以快速获取两个树部分的类别标题?

我想避免解析整个文件。

所以也许是这样做的:

var first = getXMLTitle("myXMLRoot/tree(0)/category[title]");
var second = getXMLTitle("myXMLRoot/tree(1)/category[title]");

我想要使用 .NET 核心深入链接到 XML 的东西。

【问题讨论】:

    标签: c# .net xml .net-core xml-parsing


    【解决方案1】:

    您可以使用此 XPath。请看下面的代码

    XPathDocument document = new XPathDocument(@"C:\somepath-to-xml\some-xml.xml");
    var navigator = document.CreateNavigator();
    var iterator = navigator.Select("myXMLRoot/tree/category/@title");
    while (iterator.MoveNext())
    {
        Console.WriteLine(iterator.Current.Value);
    }
    

    此代码遍历所有标题。在您的示例中,您有一个小错误cateogyr,但应该是category

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多