2009-11-03 17 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を使用して "忘れてしまった、ありがとう。 –

+0

np、それは起こる:) –

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(); 
} 
関連する問題