如何搜索和导航XML节点

时间:2010-05-24 22:48:47

标签: c# .net 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;
    }
}

任何意见将不胜感激。

2 个答案:

答案 0 :(得分: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;
}

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

s = 100
s = 200
s = 300

答案 1 :(得分: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);
}