Search code examples
c#xpath.net-corexmldocument

SelectNodes brings back to many results


Loading this XML works

<?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>

with that method

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

The XmlNodeList inside the iteration of documents brings back a list of ALL tifs in the XML not only the ones from the nd Node.

How would I correctly use Xpath to select a list inside the nd element?


Solution

  • Just remove "//" from SelectNodes and SelectSingleNode. The double slash is parsing the complete 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());
        }
    }