100

How to search and move 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 search for internal 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 feedback would be appreciated.

+7
c # xml
source share
2 answers

I would use xpath . It was designed specifically for this 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 in your XML file (wrapped in the root of the node), I get:

 s = 100 s = 200 s = 300 
+8
source share

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); } 
+4
source share

All Articles