Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing XML content - C#

Tags:

c#

xml

asp.net

I have not used XML for very long and need to extract the useful information from an XML response. If there are 2 tags that are the same but have a different name e.g

    <lst name = "stack">
       <str>Ola</str>
       <lst name = "overflow">
          <str>Hello</str>
       </lst>
     </lst>

How would I extract the contents of the tag with name="overflow"?

like image 336
Allan Macmillan Avatar asked Jul 21 '26 07:07

Allan Macmillan


2 Answers

You can use LINQ To XML:

var result = XDocument.Parse(xml)
                .Descendants("lst")
                .Where(e => (string) e.Attribute("name") == "overflow")
                .Descendants("str")
                .Select(x => x.Value)
                .FirstOrDefault();
like image 85
cuongle Avatar answered Jul 23 '26 21:07

cuongle


Try this to start:

XPathDocument docNav = new XPathDocument(pathName);
XPathNavigator nav = docNav.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(nav.NameTable);

string val =  nav.SelectSingleNode(@"/lst/lst[@name='overflow']/str")

These are good resources for simple XPath navigation and .NET XML Parsing:

http://www.w3schools.com/xpath/

http://www.codeproject.com/Articles/52079/Using-XPathNavigator-in-C

like image 41
Ryan Avatar answered Jul 23 '26 22:07

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!