11
votes

Quel est l'équivalent à Innertext à Linq-to-XML?

Mon XML est:

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


0 commentaires

5 Réponses :


16
votes

pour votre échantillon particulier: xxx pré>

Toutefois, notez que les descendants peuvent renvoyer plusieurs résultats si vous aviez un échantillon XML plus grand: P>

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


1 commentaires

J'avais essayé et j'avais eu une erreur sur célibataire (), je avais eu "à l'aide de system.xml.linq" mais j'ai oublié "à l'aide du système.linq", merci.



0
votes
string location = doc.Descendants("Location").Single().Value;

0 commentaires

0
votes
string location = (string)xdoc.Root.Element("Location");

0 commentaires

4
votes
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();
}

0 commentaires

0
votes

Dans un cas simple avec l'élément unique, xxx pré>

plusieurs éléments tels que celui-ci, P>

<CurrentWeather>
    <Location>Berlin</Location>
    <Location>Auckland</Location>
   <Location>Wellington</Location>
</CurrentWeather>

  foreach (var result in xDocument.Descendants("CurrentWeather").Select(x => new{ location = x.Element("Location").Value.Tostring() }))
        {
          Locations + = location ;
        }


0 commentaires