2009-11-03 8 views
9

Mi XML es:¿Cuál es el equivalente a InnerText en LINQ-to-XML?

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

Quiero la cadena "Berlín", ¿cómo obtener el contenido del elemento Ubicación, algo así como InnerText?

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

las anteriores declaraciones de

System.Xml.Linq.XContainer + d__a

Respuesta

15

Para su muestra particular:

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

Sin embargo, tenga en cuenta que los descendientes pueden volver resultados múltiples si tenía una muestra XML más grande:

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

El código para el anterior cambiaría a:

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

Había intentado eso y estaba recibiendo un error en Individual(), resultó que había "utilizando System.Xml.Linq "pero lo olvidé" usando System.Linq ", gracias. –

+0

np, sucede :) –

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(); 
} 
Cuestiones relacionadas