【问题标题】:How to Search and Navigate XML Nodes如何搜索和导航 XML 节点
【发布时间】:2010-05-24 22:48:47
【问题描述】:

我有以下 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> 

我想获取每个&lt;MXPWR&gt; 的内部文本。但是,不允许使用 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;
    }
}

任何意见将不胜感激。

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 完美使用 Linq 消除对 Xpath 的需求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多