c# – 如何搜索和导航XML节点

前端之家收集整理的这篇文章主要介绍了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>

我想获得每个< 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;
    }
}

任何意见将不胜感激.

解决方法

我会使用 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;
}

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

s = 100
s = 200
s = 300
原文链接:https://www.f2er.com/csharp/100793.html

猜你在找的C#相关文章