2009-11-03 35 views
9

XML của tôi là:Tương đương với InnerText trong LINQ-to-XML là gì?

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

Tôi muốn chuỗi "Berlin", làm thế nào để có được nội dung ra khỏi phần tử Location, một cái gì đó giống như innerText?

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

lợi nhuận trên

System.Xml.Linq.XContainer + d__a

Trả lời

15

Đối với mẫu cụ thể của bạn:

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

Tuy nhiên, lưu ý rằng hậu duệ có thể trở lại nhiều kết quả nếu bạn có mẫu XML lớn hơn:

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

Mã cho trên sẽ thay đổi để:

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

tôi đã cố gắng đó và đã nhận được một lỗi trên đơn(), hóa ra tôi đã "sử dụng System.Xml.Linq "nhưng quên" bằng System.Linq ", cảm ơn. –

+0

np, điều đó xảy ra :) –

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(); 
} 
Các vấn đề liên quan