2009-11-03 42 views
9

我的XML是:LINQ-to-XML中的InnerText等價於什麼?

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

我希望字符串 「柏林」,如何獲取內容到元件的位置,像的innerText

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

以上的回報

System.Xml.Linq.XContainer + d__a

回答

15

爲特定的樣本:

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

但是請注意,後代可以返回多個結果,如果你有一個更大的XML樣本:

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

對於上面的代碼將變爲:

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

我已經試過了,並在單()得到了一個錯誤,原來我有「使用System.Xml.Linq「,但忘了」使用System.Linq「,謝謝。 – 2009-11-03 15:32:42

+0

np,它發生:) – 2009-11-03 15:38:03

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(); 
} 
相關問題