2010-05-24 11 views
7

Ho il seguente XML:come cercare e navigare XML nodi

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

voglio ottenere il testo interno di ogni <MXPWR>. tuttavia, non è consentito utilizzare ID # per individuare il testo interno poiché non è sempre lo stesso. ecco il mio codice:

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

Qualsiasi parere sarà apprezzato.

risposta

8

Vorrei utilizzare xpath. È stato progettato proprio per questo tipo di problema. Qualcosa di simile:

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

Quando ho eseguito questo sul vostro file XML (avvolto in un nodo principale) ottengo:

s = 100 
s = 200 
s = 300 
4

userei 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 Perfetto per Linq per eliminare la necessità di Xpath. –

Problemi correlati