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>
CodePudding user response:
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");
CodePudding user response:
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
List<Amp> amps = new List<Amp>();
XDocument doc = XDocument.Load(FILENAME);
foreach(XElement config_set in doc.Descendants("config_set"))
{
string name = (string)config_set.Attribute("name");
string configZ = (string)config_set.Attribute("config_z");
foreach(XElement measurement in config_set.Elements("measurement"))
{
string group = (string)measurement.Attribute("group");
string pinGroup = (string)measurement.Attribute("measurement_pingroup");
decimal high = (decimal)config_set.Descendants("limit_high").FirstOrDefault();
decimal low = (decimal)config_set.Descendants("limit_low").FirstOrDefault();
Amp amp = new Amp() { name = name, configZ = configZ, group = group, pinGroup = pinGroup, high = high, low = low };
amps.Add(amp);
}
}
}
}
public class Amp
{
public string name { get; set; }
public string configZ { get; set; }
public string group { get; set; }
public string pinGroup { get; set; }
public decimal high { get; set; }
public decimal low { get; set; }
}
}