I have the following sample XML-file:
<response location='location1'>
<meas name='mt1'>14</meas>
<meas name='mt2'>23</meas>
<meas name='mt3'>65</meas>
<meas name='mt4'>31</meas>
<meas name='mt6'>32</meas>
</response>
I can retrieve the inner values, but I am trying to also dynamically retrieve "name" value of each childnode, ie: 'mt1', 'mt2', etc.
How would one go about doing this in XmlDocument?
CodePudding user response:
Given the XML structure provided and an XmlDocument
, query for the meas
nodes and then get the attribute values:
static string xml = @"<response location='location1'>
<meas name='mt1'>14</meas>
<meas name='mt2'>23</meas>
<meas name='mt3'>65</meas>
<meas name='mt4'>31</meas>
<meas name='mt6'>32</meas>
</response>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var nodes = doc.SelectNodes("//response/meas");
foreach (XmlElement e in nodes)
{
Console.WriteLine(e.GetAttribute("name"));
}
Result:
mt1
mt2
mt3
mt4
mt6
Alternatively, directly query the attributes:
var attrs = doc.SelectNodes("//response/meas/@name");
foreach (XmlAttribute e in attrs)
{
Console.WriteLine(e.Value);
}