2009-11-03 16 views
9

Moje XML jest:Co to jest odpowiednik InnerText w LINQ-to-XML?

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

chcę ciąg "Berlin", w jaki sposób uzyskać zawartość z elementu Lokalizacja, coś innerText?

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

powyższe powraca

System.Xml.Linq.XContainer + d__a

Odpowiedz

15

Dla danej próbki:

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

jednak pamiętać, że może wrócić Potomkowie wiele wyników, jeśli masz większą próbkę XML:

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

Kod do powyższego byłoby zmienić na:

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

Próbowałem tego i był coraz błąd na pojedynczy(), okazało się, ja „za pomocą System.Xml.Linq "ale zapomniałem" używając System.Linq ", dziękuję. –

+0

np, to się dzieje :) –

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(); 
} 
Powiązane problemy