微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SelectNodes 带回许多结果

如何解决SelectNodes 带回许多结果

加载此 XML 有效

<?xml version="1.0" encoding="utf-8" ?>
<export>
    <document ID="uuuid_1">
        <Property Name="PersonName" Value="bob"></Property>
        <Property Name="FileName" Value="bob.tif">
            <Reference Link="company\export\uuuid_1_423_bob.tif"/>              
        </Property>
        <Property Name="FileName" Value="bob.txt">
            <Reference Link="company\export\uuuid_1_123_bob.txt"/>
        </Property>
        <Property Name="FileName" Value="bob.tif">
            <Reference Link="company\export\uuuid_1_123_bob.tif"/>
        </Property>
    </document>
    <document ID="uuuid_2">
        <Property Name="PersonName" Value="mary"></Property>
        <Property Name="FileName" Value="mary.tif">
            <Reference Link="company\export\uuuid_2_456_mary.tif"/>
        </Property>
        <Property Name="FileName" Value="mary.txt">
            <Reference Link="company\export\uuuid_2_567_mary.txt"/>
        </Property>
    </document>
</export>

用那个方法

static void XmlLoader(string xml_path)
{
    Console.WriteLine("Loading " + xml_path);
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(xml_path);
    XmlNodeList nodes_document = xmldoc.SelectNodes("/export/document");
    foreach (XmlNode nd in nodes_document)
    {
        string Id = nd.Attributes["ID"].Value.ToString();
        string name = nd.SelectSingleNode("//Property[@Name='PersonName']/@Value").InnerText;
        XmlNodeList files = nd.SelectNodes("//Property[@Name='FileName'][contains(@Value,'.tif')]/Reference/@Link");
        Console.WriteLine(files.ToString());
    }
}

文档迭代中的 XmlNodeList 会带回 XML 中所有 tif 的列表,而不仅仅是来自 nd 节点的那些。

如何正确使用 Xpath 选择 nd 元素内的列表?

解决方法

只需从 SelectNodesSelectSingleNode 中删除“//”。双斜线是解析完整的xml

static void XmlLoader(string xml_path)
{
    Console.WriteLine("Loading " + xml_path);
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(xml_path);
    XmlNodeList nodes_document = xmldoc.SelectNodes("/export/document");
    foreach (XmlNode nd in nodes_document)
    {
        string Id = nd.Attributes["ID"].Value.ToString();
        string name = nd.SelectSingleNode("Property[@Name='PersonName']/@Value").InnerText;
        XmlNodeList files = nd.SelectNodes("Property[@Name='FileName'][contains(@Value,'.tif')]/Reference/@Link");
        Console.WriteLine(files.ToString());
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。