2010-05-24 10 views
7

tengo el siguiente código XML:Cómo buscar y navegar XML nodos

<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> 

que desea obtener el texto interno de cada <MXPWR>. sin embargo, no está permitido usar ID # para localizar el texto interno, ya que no siempre es el mismo. aquí está mi código:

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; 
    } 
} 

Cualquier opinión será apreciada.

Respuesta

8

Yo usaría xpath. Fue diseñado para este tipo de problema. Algo así como:

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; 
} 

Cuando ejecuto esto en su archivo XML (envuelto en un nodo raíz) me sale:

s = 100 
s = 200 
s = 300 
4

me gustaría utilizar 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); 
} 
+0

Uso perfecto para LINQ para eliminar la necesidad de Xpath. –

Cuestiones relacionadas