Perform a way to get one element from XML - C #

I got the XML as follows:

<Body>
  <Schoolyear>2016</Schoolyear>
  <ClassLeader>
    <Id>200555</Id>
    <Name>Martin</Name>
    <Short>ma</Short>
  </ClassLeader>
  <Info>
     some very useful information :)
  </Info>
</Body>

I need only one tag, e. academic year

I tried this:

foreach (XElement element in Document.Descendants("Schoolyear"))
{
   myDestinationVariable = element.Value;
}

It works, but I think maybe there is a more efficient and simpler solution.

+4
source share
1 answer

You can use it with LINQor just use Elementwith the specified XName

Add namespace

using System.Xml.Linq;

And use one of these examples

        string xml = @"<Body>
  <Schoolyear>2016</Schoolyear>
  <ClassLeader>
    <Id>200555</Id>
    <Name>Martin</Name>
    <Short>ma</Short>
  </ClassLeader>
  <Info>
     some very useful information :)
  </Info>
</Body>";

 XDocument dox = XDocument.Parse(xml);

 var exampl1 = dox.Element("Body").Element("Schoolyear").Value;

 var exampl2 = dox.Descendants().FirstOrDefault(d => d.Name == "Schoolyear").Value;
+2
source

Source: https://habr.com/ru/post/1662258/


All Articles