Home > database >  Simplest way to parse the element in this XML C#
Simplest way to parse the element in this XML C#

Time:06-29

Pretty new at C# so trying to learn xml serialization. I have an xml setup like the following:

<Guy>
<Name>
    <Root> 
        <Entry>
            <Favorite> his favorite food is sushi </Favorite>
        </Entry>
    </Root>
</Name>
</Guy>

I need to select the "Favorite" tags and return the "his favorite food is sushi". What is the simplest way to go about this in C#? Can XDocument and LINQ extensions be used?

CodePudding user response:

string xml = @"
<Guy>
<Name>
    <Root> 
        <Entry>
            <Favorite> his favorite food is sushi </Favorite>
        </Entry>
    </Root>
</Name>
</Guy>";
        
var doc = XDocument.Parse(xml);
Console.WriteLine(doc.Descendants("Favorite").First().Value);

// or 

foreach(var item in doc.Descendants("Favorite").Select(e => e.Value))
{
   Console.WriteLine(item);
}

https://dotnetfiddle.net/Iagop5

CodePudding user response:

You can try this approach using XPathNavigator:

    public static string GetAttribute(string xml, string nodeName) {
      StringReader stringReader = new StringReader(xml);
      XPathDocument doc = new XPathDocument(stringReader);
      XPathNavigator xNav = doc.CreateNavigator();
      XPathNavigator node = xNav.SelectSingleNode("//"   nodeName);
      return node != null ? node.InnerXml : string.Empty;
  }

Here's a reference: https://docs.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathnavigator.selectsinglenode?view=net-6.0

  • Related