如何搜索和导航XML节点

use*_*406 7 .net c# xml

我有以下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> 
Run Code Online (Sandbox Code Playgroud)

我想得到每个的内在文本<MXPWR>.但是,不允许使用ID#来定位内部文本,因为它并不总是相同的.这是我的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

任何意见将不胜感激.

Jus*_* R. 8

我会用xpath.它专为此类问题而设计.就像是:

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;
}
Run Code Online (Sandbox Code Playgroud)

当我在你的XML文件上运行它(包装在根节点中)时,我得到:

s = 100
s = 200
s = 300
Run Code Online (Sandbox Code Playgroud)


Dom*_*nic 5

我会使用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);
}
Run Code Online (Sandbox Code Playgroud)