Search code examples
c#xmlxpathxmlnode

XML count of Nodes is 0 C#


I have some xml with the following C# code I try to read some tags values. But xmlNode count is 0, can't understand why.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"C:\\myXmls\\new1.xml");

XmlNode root = xmlDocument.DocumentElement;
XmlNodeList xmlNode = root.SelectNodes("/config_set/measurement/setting");
foreach (XmlNode xn in xmlNode)
{
    string limit_high = xn["limit_high"].InnerText;
    string limit_low = xn["limit_low"].InnerText;
    Console.WriteLine("Name: {0} {1}", limit_high, limit_low);
}

Xml:

<Amp_config>
    <config_set name="myconfig1"    config_z = "FirstConfig">
        <measurement group="A1" measurement_pingroup="SYBER1">
            <setting>     
                <limit_high>0.00003719</limit_high>
                <limit_low>-0.000010</limit_low>          
            </setting>
        </measurement>  
        <measurement group="A2" measurement_pingroup="SYBER2">
            <setting>             
                <limit_high>0.00003712</limit_high>
                <limit_low>-0.000015</limit_low>                                
            </setting>
        </measurement>              
    </config_set>
    <config_set name="myconfig2"    config_z = "SecondConfig">
        <measurement group="A1" measurement_pingroup="SYBER1">
            <setting>                     
                <limit_high>0.00044</limit_high>
                <limit_low>-0.00078</limit_low>      
            </setting>
        </measurement>    
        <measurement group="A2" measurement_pingroup="SYBER2">
            <setting>             
                <limit_high>0.000565</limit_high>
                <limit_low>-0.00412</limit_low>                             
            </setting>
        </measurement>              
    </config_set>
</Amp_config>

Solution

  • Your xPath query is wrong. The simpliest fix is this:

    XmlNodeList xmlNode = root.SelectNodes("//setting");
    

    Or if you specify the full path of setting nodes then you will get the same result

    XmlNodeList xmlNode = root.SelectNodes("/Amp_config/config_set/measurement/setting");