Solved

Reading XML data using C#

Posted on 2008-10-23
8
1,064 Views
Last Modified: 2013-12-17
I have an XML data in the format as below:-

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
  <Books>
    <Key>key1</Key>
    <Value>value1</Value>
    <Key>key2</Key>
    <Value>value2</Value>
  </Books>
  <CDS>
    <Key>key1</Key>
    <Value>value1</Value>
    <Key>key2</Key>
    <Value>value2</Value>
  </CDS>
</Data>

I need to parse this xml file i.e. I need to read the key1/value1 data under Books and CDS element and insert into the database.

How do I do it in C#
0
Comment
Question by:intikhabk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22788530
The .NET framework allows you to utilize the power of XPath to access your XML data.

A brilliant article on the subject: http://www.codeproject.com/KB/cpp/myXPath.aspx

I would strongly suggest changing the XML document layout to group the various attributes of your elements. A particular book has a key and a value:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

 
    <!-- Either like this -->
   
   
 
 
    <!-- Or like this -->
   
      key1
      value1
   
   
      key2
      value2
   
 


If you were to use a design like the above, then you could enumerate your books in a similar way to how the article describes using XPath.
XPathDocument doc = new XPathDocument("books.xml");
XPathNavigator nav = doc.CreateNavigator();
 
XPathExpression books = nav.Compile("/data/books/book");
XPathNodeIterator iterator = nav.Select(books);
 
try
{
  while (iterator.MoveNext())
  {
     XPathNavigator active = iterator.Current;
     string key = active.GetAttribute("key", null);
     string value = active.GetAttribute("value", null);
  }
}
catch(Exception ex) 
{
   Console.WriteLine(ex.Message);
}

Open in new window

0
 

Author Comment

by:intikhabk
ID: 22788691
I tried running the code but the string key and string value return empty values...
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22788928
In my ASP.NET website this appears to work, I tried this in a fresh C# Windows Application and discovered that, as you say, the values are null.

To resolve this specify "" or String.Empty instead of null.

The only difference between my window app and asp.net app is that one is loading the XML from a file, and the other from an InputStream.

            XPathDocument doc = new XPathDocument("c:\\books.xml");
            XPathNavigator nav = doc.CreateNavigator();
 
            XPathExpression books = nav.Compile("/Data/Books/Book");
            XPathNodeIterator iterator = nav.Select(books);
 
            try
            {
                while (iterator.MoveNext())
                {
                    XPathNavigator active = iterator.Current;
                    string key = active.GetAttribute("key", String.Empty);
                    string value = active.GetAttribute("value", String.Empty);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

Open in new window

0
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 

Author Comment

by:intikhabk
ID: 22789050
what is incorrect in the XML I gave as an example...

how do i retrieve the value with the XML i gave...
0
 

Author Comment

by:intikhabk
ID: 22789078
also for the CDS how do i set the path...
0
 
LVL 26

Accepted Solution

by:
Anurag Thakur earned 500 total points
ID: 22789132
in your xml you cannot find which key is linked to which value
i will recommend you to use something like numberkruncher suggested in the Books section
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
  <Books>
    <Book key="key1" value="value1" />
    <Book key="key2" value="value2" />
  </Books>
</Data>

if you have a sample like this then you can read the key and values as i am going to display below

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\abc.xml");

XmlNodeList list = doc.SelectNodes("//Data/Books/Book"); // this will return all the Book nodes under Data --> Books
if (list != null)
{
      for (int i= 0; i < list.Count; i++)
      {
            Console.WriteLine("Key :" + list[0].Attributes.GetNamedItem("key").Value.ToString());
             Console.WriteLine ("Value :" + list[0].Attributes.GetNamedItem ("value").Value.ToString ());
      }
}

similarly you can do the same for CD's
0
 

Author Comment

by:intikhabk
ID: 22789210
thanks for the explanation
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22789263
The CDS would work in pretty much the same way as with the Books.

When I made the original recommendation for changing your XML, I demonstrated two ways. For your scenario I think I would be keen to go with the

I prefer the XPathDocument because it only uses read-only access to the XML document. In some scenarios this can perform more efficiently than XmlDocument where read-only access is required. If you are also going to be writing to the document then as ragi0017 illustrates, it is better to use XmlDocument.
            XPathDocument doc = new XPathDocument("c:\\books.xml");
            XPathNavigator nav = doc.CreateNavigator();
            XPathNodeIterator iterator;
 
            XPathExpression books = nav.Compile("/Data/Books/Book");
            XPathExpression cds = nav.Compile("/Data/CDS/CD");
 
            try
            {
                iterator = nav.Select(books);
                while (iterator.MoveNext())
                {
                    XPathNavigator active = iterator.Current;
                    string key = active.GetAttribute("key", String.Empty);
                    string value = active.GetAttribute("value", String.Empty);
                }
                iterator = nav.Select(cds);
                while (iterator.MoveNext())
                {
                    XPathNavigator active = iterator.Current;
                    string key = active.SelectSingleNode("Key").Value;
                    string key = active.SelectSingleNode("Value").Value;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

Open in new window

0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question