2009-11-03 26 views
9

Benim XML'dir: LINQ-to-XML'de InnerText'e eşdeğer nedir?

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

Ben dize "Berlin" istemek, nasıl eleman dışına içeriğini alabilirim Yer, innerText gibi bir şey?

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

yukarıdaki döner

System.Xml.Linq.XContainer belirli numune için + d__a

cevap

15

: Ancak

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

, The Descendants iade unutmayın Daha büyük bir XML örneğiniz varsa birden çok sonuç:

için
<root> 
<CurrentWeather> 
    <Location>Berlin</Location> 
</CurrentWeather> 
<CurrentWeather> 
    <Location>Florida</Location> 
</CurrentWeather> 
</root> 

yukarıdaki kod değiştirecek: Ben çalıştı ve Tek() üzerinde bir hata başlamıştı

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

, ben "seçeneğini kullanarak vardı çıktı System.Xml.Linq "ama System.Linq kullanarak unuttum", teşekkürler. –

+0

np, bu oluyor :) –

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(); 
} 
İlgili konular