user349406
user349406

Reputation: 71

How to Search and Navigate XML Nodes

I have the following XML :

<LOCALCELL_V18 ID = "0x2d100000">
  <MXPWR ID = "0x3d1003a0">100</MXPWR> 
</LOCALCELL_V18>
<LOCALCELL_V18 ID = "0x2d140000">
  <MXPWR ID = "0x3d1403a0">200</MXPWR>  
</LOCALCELL_V18>
<LOCALCELL_V18 ID = "0x2d180000">  
  <MXPWR ID = "0x3d1803a0">300</MXPWR>   
</LOCALCELL_V18> 

I want to get the inner text of each <MXPWR>. however, it is not allowed to use ID# to locate the inner text since it is not always the same. here is my code:

XmlNodeList LocalCell = xmlDocument.GetElementsByTagName("LOCALCELL_V18");

foreach (XmlNode LocalCell_Children in LocalCell)
{
    XmlElement MXPWR = (XmlElement)LocalCell_Children;
    XmlNodeList MXPWR_List = MXPWR.GetElementsByTagName("MXPWR");
    for (int i = 0; i < MXPWR_List.Count; i++)
    {
       MaxPwr_form_str = MXPWR_List[i].InnerText;
    }
}

Any opinion will be appreciated.

Upvotes: 7

Views: 14008

Answers (2)

Domenic
Domenic

Reputation: 112857

I would use XLinq:

using System.Xml.Linq;

var xDoc = XDocument.Load("data.xml");

var mxpwrs = xDoc.Descendants("MXPWR");
foreach (var mxpwr in mxpwrs)
{
    Console.WriteLine(mxpwr.Value);
}

Upvotes: 7

Justin R.
Justin R.

Reputation: 24061

I would use xpath. It was designed for just this sort of problem. Something like:

using System.Xml;
using System.Xml.XPath;
....
string fileName = "data.xml"; // your file here
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();

// Compile an xpath expression
XPathExpression expr = nav.Compile("./LOCALCELL_V18/MXPWR");
XPathNodeIterator iterator = nav.Select(expr);

// Iterate on the node set
while (iterator.MoveNext())
{
    string s = iterator.Current.Value;
}

When I run this on your XML file (wrapped in a root node) I get:

s = 100
s = 200
s = 300

Upvotes: 10

Related Questions