2009-11-03 2 views
9

mio XML è:Qual è l'equivalente di InnerText in LINQ-to-XML?

<CurrentWeather> 
    <Location>Berlin</Location> 
</CurrentWeather> 

voglio la stringa "Berlino", come si fa ottenere contenuti fuori dell'elemento Località, qualcosa come InnerText?

XDocument xdoc = XDocument.Parse(xml); 
string location = xdoc.Descendants("Location").ToString(); 

i rendimenti superiori

System.Xml.Linq.XContainer + d__a

risposta

15

per il vostro campione particolare:

string result = xdoc.Descendants("Location").Single().Value; 

Si noti tuttavia che possano tornare Discendenti più risultati se disponevi di un campione XML più grande:

<root> 
<CurrentWeather> 
    <Location>Berlin</Location> 
</CurrentWeather> 
<CurrentWeather> 
    <Location>Florida</Location> 
</CurrentWeather> 
</root> 

Il codice per quanto sopra cambierebbe a:

foreach (XElement element in xdoc.Descendants("Location")) 
{ 
    Console.WriteLine(element.Value); 
} 
+0

avevo provato questo e stavo ottenendo un errore singolo(), si è rivelato che avevo "utilizzando System.Xml.Linq "ma ho dimenticato" using System.Linq ", grazie. –

+0

np, succede :) –

1
string location = doc.Descendants("Location").Single().Value; 
0
string location = (string)xdoc.Root.Element("Location"); 
1
public static string InnerText(this XElement el) 
{ 
    StringBuilder str = new StringBuilder(); 
    foreach (XNode element in el.DescendantNodes().Where(x=>x.NodeType==XmlNodeType.Text)) 
    { 
     str.Append(element.ToString()); 
    } 
    return str.ToString(); 
}