Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Search and Navigate XML Nodes

Tags:

c#

.net

xml

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.

like image 425
user349406 Avatar asked May 24 '10 22:05

user349406


1 Answers

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
like image 51
Justin R. Avatar answered Sep 26 '22 12:09

Justin R.