Home > DeveloperSection > Forums > How to parsing XML and extracting nodes?
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    January-27-2015 10:14 PM

 ASP.Net C#  XML  XML Parsing 
Ratings:


 1 Reply(s)
 585  View(s)
Rate this:

I have the following XML:

<bookstore>

    <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>

        <title>The Autobiography of Benjamin Franklin</title>

        <author>

            <first-name>Benjamin</first-name>

            <last-name>Franklin</last-name>

        </author>

        <price>8.99</price>

    </book>

</bookstore>

I want to read it and display the result as following:

Genre: autobiography

Publication: 1981-03-22

ISBN: 1-861003-11-0

Title: The Autobiography of Benjamin Franklin

Author: Benjamin Franklin

Price: 8.99



Takeshi Okada
Takeshi Okada

Total Post:89

Points:629
Posted on    January-27-2015 10:39 PM


Here you have some example code to do this with XElement:

   

 var xml = XElement.Load("test.xml");

 

    foreach (var bookEl in xml.Elements("book"))

    {

        Console.WriteLine("Genre: " + bookEl.Attribute("genre").Value

            + " " + "Publication: " + bookEl.Attribute("publicationdate").Value

            + " " + "ISBN: " + bookEl.Attribute("ISBN").Value);

        Console.WriteLine("Title: " + bookEl.Element("title").Value);

        Console.WriteLine("Author: " + bookEl.Element("author").Element("first-name").Value

            + " " + bookEl.Element("author").Element("last-name").Value);

        Console.WriteLine("Price: " + bookEl.Element("price").Value);

    }


Modified On Mar-14-2016 12:22:51 AM

Don't want to miss updates? Please click the below button!

Follow MindStick