Home > Software Development > Parsing XML in C#: A Quick Working Sample

Parsing XML in C#: A Quick Working Sample

August 9th, 2013 Leave a comment Go to comments

Just started to work on hacking the Web application of vCAC and REST APIs in C#. As expected, the XML processing is an indispensable part for that purpose. I have worked on C# on and off in the past, but never as consistently as on Java. To get myself familiar with the related C# APIs for parsing, I coded the following sample code.

using System;
using System.Collections.Generic;
using System.Xml;
 
namespace org.doublecloud
{
    class XmlParsingDemo
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"c:\users\steve\documents\books.xml");
 
            XmlNodeList nodes = doc.DocumentElement.SelectNodes("/catalog/book");
 
            List<Book> books = new List<Book>();
 
            foreach (XmlNode node in nodes)
            {
                Book book = new Book();
 
                book.author = node.SelectSingleNode("author").InnerText;
                book.title = node.SelectSingleNode("title").InnerText;
                book.id = node.Attributes["id"].Value;
 
                books.Add(book);
            }
 
            System.Console.WriteLine("Total books: " + books.Count);
        }
    }
 
    class Book
    {
        public string id;
        public string title;
        public string author;
    }
}

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

The following is a sample XML for running the code. The content has duplications but is still good for trying out the above program.

<?xml version="1.0"?>
<catalog>
  <book id="bk101">
    <author>Steve Jin</author>
    <title>VMware VI and vSphere SDK</title>
    <genre>Computer</genre>
    <price>59.99</price>
    <publish_date>2009-09-01</publish_date>
    <description>
      An in-depth introduction on VMware vSphere SDK and open source vijava API.
    </description>
  </book>
  <book id="bk102">
    <author>Steve Jin</author>
    <title>TBD</title>
    <genre>Computer</genre>
    <price>59.99</price>
    <publish_date>2015-09-01</publish_date>
    <description>
      An in-depth introduction on something.
    </description>
  </book>
</catalog>
Categories: Software Development Tags: , ,
  1. Pierre Lainé
    August 9th, 2013 at 04:21 | #1

    Hi steve

    sorry to post here but I didn’t now where to contact you in private.

    I made a tutorial on the VI Java API on the VMware communities web site and maybe it will help developers to use your API.

    http://communities.vmware.com/people/pierreLx/blog/2013/08/07/using-vi-java-api-tutorial

    You did an amazing job!

    Regards
    Pierre

  2. August 9th, 2013 at 11:57 | #2

    Thanks Pierre,

    Great job in writing up the tutorial! I will add a link to it from the project home.

    Steve

  3. August 12th, 2013 at 01:59 | #3

    Hi Pierre,

    Just updated the project Web site with a news on your tutorial. Also added the link to my existing tutorial.

    Thanks again for your great work!

    Steve

  4. Pierre
    September 26th, 2013 at 01:25 | #4

    Hi sorry for the late reply,
    thanks a lot for adding a link to my tutorial, lot of views since 1 month 😉

    Pierre

  5. September 26th, 2013 at 01:52 | #5

    You are very welcome Pierre! Please let me know more good stuff from your side. :)

    Steve

  6. pierre
    September 26th, 2013 at 05:24 | #6

    Yes, still looking for ideas but since I am working for the AREVA group in the VMware team, security didn’t let me try my programs so not a lot of motivation to continue the project…
    Do you mind if I add you on linkedin? my mail address is pierre.laine2@gmail.com.

    Pierre

  7. Lamia
    October 5th, 2013 at 00:33 | #7

    i’m having a problem , could you help me ?

  8. mushy
    October 10th, 2013 at 05:54 | #8

    hey i have to ask if i want to print the name and the author of the book what should i do then ?????

  9. CP
    March 3rd, 2014 at 11:19 | #9

    Hi,

    Good job, quite good for a quick startup :)

  10. April 3rd, 2014 at 00:55 | #10

    XmlDataDocument xmldoc = new XmlDataDocument();
    XmlNodeList xmlnode ;
    int i = 0;
    string str = null;
    FileStream fs = new FileStream(“product.xml”, FileMode.Open, FileAccess.Read);
    xmldoc.Load(fs);
    xmlnode = xmldoc.GetElementsByTagName(“Product”);

    Full source : http://csharp.net-informations.com/xml/how-to-read-xml.htm

    elvaris

  11. Praveen
    December 9th, 2014 at 01:41 | #11

    Hi, Thank you.
    I was planning to apply the same logic to generate the list of the policies available in my XML file. seems to be not working as i have the tag name like “Q12:Policy”. It is not able to read the tag though i declared it as a string seperatly and called in the list.
    Is there any way i can share my code so that some one can help me out?
    Thanks in advance

  12. Praveen
    December 9th, 2014 at 02:02 | #12

    My code is:
    private void button1_Click(object sender, EventArgs e)
    {

    {
    XmlDocument doc = new XmlDocument();
    doc.Load(@”c:\Temp\RSOP.xml”);

    XmlNodeList nodes = doc.DocumentElement.SelectNodes(“/RSOP/ComputerResults/EntensionData/Extension”);
    String Policy;
    Policy = (“q12:Policy”);
    List books = new List();

    foreach (XmlNode node in nodes)
    {
    Policy Policy = new Policy();

    Policy.Name = node.SelectSingleNode(“q12:Name”).InnerText;
    Policy.Value = node.SelectSingleNode(“q12:Value”).InnerText;
    Policy.catagory = node.Attributes[“q12:Catagory”].InnerText;

    Policy.Add(Policy);

    }

    }

    And My XML is :

    Allow active scripting
    Windows Components/Internet Explorer/Internet Control Panel/SecurityPage/Trusted Sites

    Enabled

    Enable

    And it is having many Policy tags( I just copied only one policy) under .

    Any help would be great.

  13. Ryan
    February 3rd, 2015 at 18:09 | #13

    This is awesome… Except that it doesn’t work, at least not in Visual Studio.

    On this line:

    List books = new List();

    “Book” is highlighted as producing an error. The error is:

    The type or namespace ‘Book’ could not be found.

  14. KevvvvyP
    August 4th, 2015 at 05:47 | #14

    You’re missing a closing book tag in your xml file.

  15. August 4th, 2015 at 15:09 | #15

    Thanks a lot Kevin! Just updated it.

    -Steve

  1. December 23rd, 2013 at 00:01 | #1