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());
    }
}