?
Solved

How do I read thru an XML doc (in C#) and get the value of each node in succession?

Posted on 2011-10-17
12
Medium Priority
?
420 Views
Last Modified: 2013-11-07
I need to read an XML doc and get the value of each node. I'm coding in C#.
0
Comment
Question by:jobrems
  • 4
  • 4
  • 2
  • +2
12 Comments
 
LVL 5

Expert Comment

by:Kelaros
ID: 36982218
There is a class you can use in C# .NET called XmlReader, it's pretty easy to use, here's the link for the documentation:

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader%28v=vs.71%29.aspx
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36982297
Hello, some examples:
string myXmlText = "<Root><Item>1</Item><Item>2</Item><Item>3</Item></Root>";

// Example 1 (better performance for large data)
using (System.IO.StringReader sr = new StringReader(myXmlText))
{
    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
    {
        while (reader.Read())
        {
            Console.WriteLine(reader.ReadString());
        }
    }
}

// Example 2 (you can use XPath)
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(myXmlText);
foreach (System.Xml.XmlNode node in xmlDoc.SelectNodes("Root/Item"))
{
    Console.WriteLine(node.InnerText);
}

Open in new window

0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36982305
I'd say it is not quite clear what you want.

To be correct, some nodes have no text values for example - they just contain other nodes. What are you expecting in this case?

XmlReader is good but I'd say it is not so easy for use. On another case using a recursion with XmlDocument etc also requires some skills.

Can you tell a bit more about your task? Is you xml a generic one, or it has some specific format?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36982565
OK, I can suggest a generic procedure for printing nodes and values. However, it works for XmlNodes. If you want for XmlElements - you need to do some alterations. I just want to demonstrate a n approach.

The xml for testinf, e.g., like below:

<?xml version="1.0"?>
<company>
  <department name="Sales">
    <head>
      <name>Roger</name>
    </head>
    <stuff>
      <employee>
        <name>Bob</name>
      </employee>
      <employee>
        <name>Mark</name>
      </employee>
      <employee>
        <name>Ingred</name>
      </employee>
      <employee>
        <name>Jack</name>
      </employee>
    </stuff>
  </department>
  <department name="Finance">
    <head>
      <name>Sally</name>
    </head>
    <stuff>
      <employee>
        <name>John</name>
      </employee>
      <employee>
        <name>Chris</name>
      </employee>
    </stuff>
  </department>
</company>

===========

Output:
company[]
department[]
head[]
name[]
#text[Roger]
stuff[]
employee[]
name[]
#text[Bob]
employee[]
name[]
#text[Mark]
employee[]
name[]
#text[Ingred]
employee[]
name[]
#text[Jack]
department[]
head[]
name[]
#text[Sally]
stuff[]
employee[]
name[]
#text[John]
employee[]
name[]
#text[Chris]

private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");
            printNode(doc.DocumentElement);

        }

        private void printNode(XmlNode node)
        {
            if (!string.IsNullOrEmpty(node.Value))
            {
                System.Diagnostics.Debug.WriteLine(node.Name + "[" + node.Value + "]");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(node.Name + "[]");
            }
            foreach (XmlNode childNode in node.ChildNodes)
            {
                printNode(childNode);
            }
        }

Open in new window

0
 

Author Comment

by:jobrems
ID: 36983018
The XML I will have to read is generic: the hierarchy will contain multiple levels. For example:

- <CommandReceived version="1">
  <barcodeSubSystemEnabled>1</barcodeSubSystemEnabled>
- <centrifugeSubSystem>
  <RPM>0</RPM>
  <ramp>175</ramp>
  <enable>0</enable>
  <stop>1</stop>
  </centrifugeSubSystem>
  <fanEnabled>1</fanEnabled>
- <buckets>
- <bucket1>
  <plasmaValveCommand>3</plasmaValveCommand>
  <plateletValveCommand>3</plateletValveCommand>
  <leukoValveCommand>3</leukoValveCommand>
  <autoCal>0</autoCal>
- <detector1>
  <gain>0</gain>
  <intensity>0</intensity>
  </detector1>
- <detector2>
  <gain>0</gain>
  <intensity>0</intensity>
  </detector2>
- <bucket>
  <gain>0</gain>
  <intensity>0</intensity>
  </bucket>
  </bucket1>
  </buckets>
  </CommandReceived>

This structure may change at any time. Thus, the approach described above by yv989c does not work.
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36983066
Hello, why you say that? the first example works, it read the content of every node (all the levels) of your xml and display it to the console:
string myXmlText = "<CommandReceived version=\"1\"><barcodeSubSystemEnabled>1</barcodeSubSystemEnabled><centrifugeSubSystem><RPM>0</RPM><ramp>175</ramp> <enable>0</enable> <stop>1</stop> </centrifugeSubSystem><fanEnabled>1</fanEnabled> <buckets><bucket1>  <plasmaValveCommand>3</plasmaValveCommand>   <plateletValveCommand>3</plateletValveCommand>   <leukoValveCommand>3</leukoValveCommand>   <autoCal>0</autoCal> <detector1>  <gain>0</gain>   <intensity>0</intensity>   </detector1><detector2>  <gain>0</gain>   <intensity>0</intensity>   </detector2><bucket>  <gain>0</gain>   <intensity>0</intensity>   </bucket>  </bucket1>  </buckets>  </CommandReceived>";

// Example 1 (better performance for large data)
using (System.IO.StringReader sr = new StringReader(myXmlText))
{
    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
    {
        while (reader.Read())
        {
            Console.WriteLine(reader.ReadString());
        }
    }
}

Open in new window

0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36983143
This example will give you clean result, I'm extracting only the nodes with value:
string myXmlText = "<CommandReceived version=\"1\"><barcodeSubSystemEnabled>1</barcodeSubSystemEnabled><centrifugeSubSystem><RPM>0</RPM><ramp>175</ramp> <enable>0</enable> <stop>1</stop> </centrifugeSubSystem><fanEnabled>1</fanEnabled> <buckets><bucket1>  <plasmaValveCommand>3</plasmaValveCommand>   <plateletValveCommand>3</plateletValveCommand>   <leukoValveCommand>3</leukoValveCommand>   <autoCal>0</autoCal> <detector1>  <gain>0</gain>   <intensity>0</intensity>   </detector1><detector2>  <gain>0</gain>   <intensity>0</intensity>   </detector2><bucket>  <gain>0</gain>   <intensity>0</intensity>   </bucket>  </bucket1>  </buckets>  </CommandReceived>";

// Example 1 (better performance for large data)
using (System.IO.StringReader sr = new StringReader(myXmlText))
{
    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
    {
        while (reader.Read())
        {
            if (reader.NodeType == System.Xml.XmlNodeType.Text && reader.HasValue)
                Console.WriteLine(reader.Value);
        }
    }
}

Open in new window

0
 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 2000 total points
ID: 36983250
Try the following code.

The output is

barcodeSubSystemEnabled[1]
RPM[0]
ramp[175]
enable[0]
stop[1]
fanEnabled[1]
plasmaValveCommand[3]
plateletValveCommand[3]
leukoValveCommand[3]
autoCal[0]
gain[0]
intensity[0]
gain[0]
intensity[0]
gain[0]
intensity[0]

What output do you want? Pls be more specific! :)
private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");
            printElement(doc.DocumentElement);

        }

        private void printElement(XmlElement ele)
        {

            //else
            //{
            //    System.Diagnostics.Debug.WriteLine(ele.Name + "[]");
            //}
            bool hasChildElements = false;
            foreach (XmlNode childNode in ele.ChildNodes)
            {
                if (childNode is XmlElement)
                {
                    hasChildElements = true;
                    printElement((XmlElement)childNode);
                }

            }
            if (!hasChildElements)
            {
                System.Diagnostics.Debug.WriteLine(ele.Name + "[" + ele.InnerText + "]");
            }
        }

Open in new window

0
 
LVL 9

Expert Comment

by:keyu
ID: 36984451
XML FILE:



<newsletter>
 <items value="article">
   <item>
    <image>car.gif</image>
    <text>text goes here</text>
    <author>bdillan/author>
    <date>070408</date>
 </item>
   <item>
    <image>car2.gif</image>
    <text>text goes here</text>
    <author>bdillan/author>
    <date>070408</date>
 </item>
 </items>
 
<items value="comics">
   <item>
    <image>comic.gif</image>
    <text>text goes here</text>
    <author>bdillan/author>
    <date>070408</date>
 </item>
   <item>
    <image>comic2.gif</image>
    <text>text goes here</text>
    <author>bdillan/author>
    <date>070408</date>
 </items>
 </newsletter>
 

SOURCE TO READ XML PATH:

   
     ReadNewsLetterXml(Server.MapPath("NewsLetter.xml"));
 
 
 
    public void ReadNewsLetterXml(string path)
     {
         System.Xml.XmlDocument Document = new System.Xml.XmlDocument();
         Document.Load(path);
 
        if (Document.HasChildNodes)
         {
             // This line below will enable you to read your full xml file
             ReadXmlNodes(Document.ChildNodes);
             
            // Uncomment the line below if you want to read article nodes
             // ReadXmlNodes(Document.SelectSingleNode("newsletter/items[@value='article']").ChildNodes);
 
            // Uncomment the line below if you want to read comic nodes
             // ReadXmlNodes(Document.SelectSingleNode("newsletter/items[@value='comics']").ChildNodes);
 
        }
     }
 

    /// <summary>
     /// This function will read the xmlnodelist selected
     /// </summary>
     /// <param name="nodeList"></param>
     public void ReadXmlNodes(System.Xml.XmlNodeList nodeList)
     {
         foreach (System.Xml.XmlNode n in nodeList)
         {
             if (n.ChildNodes.Count == 0)
             {
                 Response.Write(n.InnerText);
                 Response.Write("<br>");
             }
             else
             {
                 if (n.Attributes.Count > 0)
                 {
                     Response.Write("<b>" + n.Attributes[0].Value + "</b><br>");
                 }
                 ReadXmlNodes(n.ChildNodes);
             }
         }
     }
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36988608
keyu, I believe it is a good idea to check your code before posting. Otherwise it confuses an asker.

Your xml is not well formed. I.e. it is not xml :) There are several errors.
Code is OK, very similar to mine just written for ASP.
0
 

Author Closing Comment

by:jobrems
ID: 36993164
Thanks for the careful attention. I was expecting that .NET now included a method to recursively read all values from an XML doc. I'm surprised that I had to write a recursive routine.
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36993370
Hello jobrems, well, only to leave you this clear, yes it can be done without a recursive routine, this will give you the same output of anarki_jimbel example... don't understand why you dont see it...
string myXmlText = "<CommandReceived version=\"1\"><barcodeSubSystemEnabled>1</barcodeSubSystemEnabled><centrifugeSubSystem><RPM>0</RPM><ramp>175</ramp> <enable>0</enable> <stop>1</stop> </centrifugeSubSystem><fanEnabled>1</fanEnabled> <buckets><bucket1>  <plasmaValveCommand>3</plasmaValveCommand>   <plateletValveCommand>3</plateletValveCommand>   <leukoValveCommand>3</leukoValveCommand>   <autoCal>0</autoCal> <detector1>  <gain>0</gain>   <intensity>0</intensity>   </detector1><detector2>  <gain>0</gain>   <intensity>0</intensity>   </detector2><bucket>  <gain>0</gain>   <intensity>0</intensity>   </bucket>  </bucket1>  </buckets>  </CommandReceived>";

// Example 1 (better performance for large data)
using (System.IO.StringReader sr = new System.IO.StringReader(myXmlText))
{
    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
    {
        string lastElement = null;
        while (reader.Read())
        {
            if (reader.NodeType == System.Xml.XmlNodeType.Element)
                lastElement = reader.Name;
            else if (reader.NodeType == System.Xml.XmlNodeType.Text && reader.HasValue)
                System.Diagnostics.Debug.WriteLine(lastElement + "[" + reader.Value + "]");
        }
    }
}

Open in new window


Output:
barcodeSubSystemEnabled[1]
RPM[0]
ramp[175]
enable[0]
stop[1]
fanEnabled[1]
plasmaValveCommand[3]
plateletValveCommand[3]
leukoValveCommand[3]
autoCal[0]
gain[0]
intensity[0]
gain[0]
intensity[0]
gain[0]
intensity[0]
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
This video tutorial shows you the steps to go through to set up what I believe to be the best email app on the android platform to read Exchange mail.  Get the app on your phone: The first step is to make sure you have the Samsung Email app on your …
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

615 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