Using the XmlReader to read an xml file

  • (2 Pages)
  • +
  • 1
  • 2

25 Replies - 5478 Views - Last Post: 21 February 2014 - 06:45 AM Rate Topic: -----

#1 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Using the XmlReader to read an xml file

Posted 14 February 2014 - 09:33 AM

Hi,
I'm using the XmlReader to read an xml file and I can get some elements but not others. Here is a code snippet:

public ReadXMLFile()
        {
            InitializeComponent();

            try
            {
                using (XmlReader reader = XmlReader.Create("Star.xml"))
                {
                    while (reader.Read())
                    {
                        if(reader.IsStartElement())
                        {
                            switch (reader.Name)
                            {
                                case "Text":
                                    //reader.MoveToContent();
                                    reader.Read();

                                    break;
                                case "TextValue":
                                    reader.Read();
                                    break;


                                    
                            }
                            
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occurred." + ex);
            }



The problem seems to be the way the xml file is constructed below is a sample of it:

-<Details Level="1">
   -<Section SectionNumber="0">
      -<Text Name="Text1">
         <TextValue>NI No : JB686751D </TextValue>
       </Text>
      -<Text Name="Text2">
         <TextValue>Tax Code : 944L </TextValue>
       </Text>
      -<Text Name="Text3">
         <TextValue>Pay By : BACS</TextValue>
       </Text>
      -<Text Name="Text4">
         <TextValue>Date : 07 Feb 2014</TextValue>
       </Text>
      -<Text Name="Text5">
         <TextValue>Period : 44</TextValue>
       </Text>
      -<Text Name="Text6">
         <TextValue>NI Letter : A</TextValue>
       </Text>
      -<Text Name="Text11">
         <TextValue>Description</TextValue>
       </Text>



The data I'm after is the <Text Name="Text1"> the "Text1" part of that and the <TextValue>data here</TextValue>.

I have no control over this file by the way it comes this way and I have to use it this way. The "TextValue" element work perfectly, I just do reader.Read() until I've got "TextValue" then the reader.Read() gives me the data I require.
When I try to do the same with the "<Text Name" element I expected to be looking for "Name" but I don't find so I look for "Text" but when I do the reader.Read() it's skips right over the data in the element and goes straight to "<TextValue>".
I hope that makes some sense. Is there something other than reader.Read() I should be using? Or once I have "<Text" can I get to all of it. i.e. "Text Name="Text1">"

I look forward to hearing from you.
Regards,
Jim.

Is This A Good Question/Topic? 0
  • +

Replies To: Using the XmlReader to read an xml file

#2 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Using the XmlReader to read an xml file

Posted 14 February 2014 - 10:52 AM

Is there a specific reason you must use XmlReader? Are you required to use an older version of the .Net framework?

If you can use the newer versions, I'd suggest using the System.Xml.Linq namespace instead, XDocument is what you'd use to craete/load/modify/save an xml document.

XmlReaders only benefit is that it's not cached, which can make working with very large xml documents speedier and less memory intensive. If this is what you need, well then I can come back to your question.

This post has been edited by lordofduct: 14 February 2014 - 10:52 AM

Was This Post Helpful? 1
  • +
  • -

#3 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Re: Using the XmlReader to read an xml file

Posted 15 February 2014 - 08:00 AM

Hi,
No I don't need to use XmlReader if there is an alternative. I'm new to c# I just want to read the xml file, from which the sample comes. I've no problem getting the "NI No : JB686751D" out of "<TextValue>NI No : JB686751D </TextValue>" because the XmlReader finds "<TextValue>" but I can't get "Test1" from "<Text Name="Text1">" I think it the finds "Text" and on the next read jumps straight to "TextValue". Skipping over "Name" if you like.

If there is another method I'll happily use that.

My xml file is laid out like this:

-<Text Name="Text1">
    <TextValue>NI No : JB686751D </TextValue>
</Text>



If it was like this:

-<Text>
    <Name>="Text1"</Name>
    <TextValue>NI No : JB686751D </TextValue>
 </Text>



I would be fine. So it's essentially the "<Name>" element I'm looking for and the XmlReader is skipping over it. Would System.Linq.xml.XDocument handle it differently? I've googled it, I will have a go later with it, if you have some experience with it any help would great.

Thanks,
Jim.
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: Using the XmlReader to read an xml file

Posted 15 February 2014 - 05:34 PM

Look at the documentation for XDocument that is available in the newer versions of the .NET Framework, and learn how to use XPath queries. Those same skills will help you out when you have to do jQuery.
Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Using the XmlReader to read an xml file

Posted 16 February 2014 - 10:07 AM

I'm all for LINQ to XML, but you aren't all that far off with the XmlReader. You just have to get the attribute instead of the value of the tag. Here's a SO thread about getting attributes:

http://stackoverflow...-with-xmlreader
Was This Post Helpful? 1
  • +
  • -

#6 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Using the XmlReader to read an xml file

Posted 16 February 2014 - 10:10 AM

Here's the XDocument class:

http://msdn.microsof...(v=vs.110).aspx

This allows you to access the entire XML document at the same moment (where as XmlReader streams across the XML document, which is why it can be cumbersome to use, but has its benefits when you have memory or bandwidth constraints).

In your case it'd be pretty easy to use... something like this (I'm showing you this as it is a simple scenario, I advise playing with this a lot and learning all of it).

(note, one thing I actually prefer about VB.Net is the xml linq syntax sugar is so much nicer!)
//make sure System.Xml.Linq is being used

var xdoc = Xdocument.Load("Star.xml");

//I'm using Descendants, it gives ALL nodes somewhere in the document with the name passed in
//If you wanted the child elements of the specific node you're on, you use Element/Elements method
foreach(var xel in xdoc.Root.Descendents("Text"))
{
    var name = xel.Attribute("Name").Value;
    var txt = xel.Element("TextValue").Value; //see here, I want the direct child of the "Text" node, so I use 'Element'
}


Was This Post Helpful? 1
  • +
  • -

#7 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Using the XmlReader to read an xml file

Posted 16 February 2014 - 10:44 AM

Right. I honestly think the Linq to XML classes have an easier to understand model, and they're easier to work with too.

I realize my previous post wasn't perfectly clear. The problem is the difference between Attribute and Value. The OP is trying to read an attribute as if it were a sub node, and that wouldn't work with LINQ anymore than it does with the older XmlReader.
Was This Post Helpful? 1
  • +
  • -

#8 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 07:27 AM

View PostCurtis Rutland, on 16 February 2014 - 10:07 AM, said:

I'm all for LINQ to XML, but you aren't all that far off with the XmlReader. You just have to get the attribute instead of the value of the tag. Here's a SO thread about getting attributes:

http://stackoverflow...-with-xmlreader



Thanks Curtis that was just what I was after.
Was This Post Helpful? 0
  • +
  • -

#9 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 07:40 AM

View Postlordofduct, on 16 February 2014 - 10:10 AM, said:

Here's the XDocument class:

http://msdn.microsof...(v=vs.110).aspx
...


Thanks LordOfDuct,
I haven't had a chance to look into this yet but I will do. I've just finished a Microsoft C# Software Development Fundamentals course and they are still teaching the XmlReader method.
Regards,
Jim.

This post has been edited by andrewsw: 17 February 2014 - 08:14 AM
Reason for edit:: Reduced large quote

Was This Post Helpful? 0
  • +
  • -

#10 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 08:22 AM

Thanks LordOfDuct,
I haven't had a chance to look into this yet but I will do. I've just finished a Microsoft C# Software Development Fundamentals course and they are still teaching the XmlReader method.
Regards,
Jim.
[/quote]

Hi LordOfDuct,
I've tried that but it's not going round my foreach loop. Here's the code:
                //
                // Using XDocument instead of XmlReader
                //

                var xdoc = Xdocument.Load("Star.xml");

                // Using Descendants, it gives all nodes womewhere in to document with the name passed in
                // If I wanted the child elements of the specific node I'm on, I would use Elements/Elements method

                foreach (var xel in xdoc.Root.Descendants("Text"))
                {
                    var name = xel.Attribute("Name").Value;
                    var value = xel.Element("TextValue").Value;
                }
                


                using (XmlReader reader = XmlReader.Create("Star.xml"))



I've left the old XmlReader in there for now. When I do the Xdocument.load, xdoc contains the whole Star.xml file but when I step through the foreach loop, I step onto "foreach" then "xdoc.Root.Descendants("TextValue"))" then "in" and then I jump out of the loop to the "using XmlReader" line.

Am I doing something wrong?
Regards,
Jim.

This post has been edited by andrewsw: 17 February 2014 - 08:26 AM
Reason for edit:: Removed previous quote

Was This Post Helpful? 0
  • +
  • -

#11 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 08:28 AM

@jcborland There is no need to keep quoting a large previous post, there is a large Reply button a little further down the page. Doing so makes the topic unnecessarily long and hard to follow.
Was This Post Helpful? 0
  • +
  • -

#12 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 08:53 AM

I just ran it myself, using the test data from your first post:

using System;
using System.Xml.Linq;

namespace ConsoleTest01
{
    public class Program
    {

        static void Main(string[] args)
        {

            var xdoc = Xdocument.Load("Star.xml");

            foreach (var xel in xdoc.Root.Descendants("Text"))
            {
                Console.WriteLine(xel.Attribute("Name").Value);
                Console.WriteLine(xel.Element("TextValue").Value);
                Console.WriteLine("-------------");
            }

            Console.ReadLine();
        }

    }
}



Test Data:

<?xml version="1.0" encoding="utf-8" ?>
<Details Level="1">
  -<Section SectionNumber="0">
    -<Text Name="Text1">
      <TextValue>NI No : JB686751D </TextValue>
    </Text>
    -<Text Name="Text2">
      <TextValue>Tax Code : 944L </TextValue>
    </Text>
    -<Text Name="Text3">
      <TextValue>Pay By : BACS</TextValue>
    </Text>
    -<Text Name="Text4">
      <TextValue>Date : 07 Feb 2014</TextValue>
    </Text>
    -<Text Name="Text5">
      <TextValue>Period : 44</TextValue>
    </Text>
    -<Text Name="Text6">
      <TextValue>NI Letter : A</TextValue>
    </Text>
    -<Text Name="Text11">
      <TextValue>Description</TextValue>
    </Text>
  </Section>
</Details>



Result:

Text1
NI No : JB686751D
-------------
Text2
Tax Code : 944L
-------------
Text3
Pay By : BACS
-------------
Text4
Date : 07 Feb 2014
-------------
Text5
Period : 44
-------------
Text6
NI Letter : A
-------------
Text11
Description
-------------



(I am not sure why the 'D' in 'XDocument' keeps getting turned lowercase when I post it)
Was This Post Helpful? 0
  • +
  • -

#13 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 09:03 AM

View Postlordofduct, on 17 February 2014 - 03:53 PM, said:

(I am not sure why the 'D' in 'XDocument' keeps getting turned lowercase when I post it)

This is a problem with the post-editor and has been occurring for a while. There are a number of other terms that are problematic, such as Expression, the S in Javascript, etc..
Was This Post Helpful? 0
  • +
  • -

#14 jcborland   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 137
  • Joined: 16-December 13

Re: Using the XmlReader to read an xml file

Posted 17 February 2014 - 03:17 PM

Hi LordOfDuct,
I've just shortened the xml file to what you have used and it works so there must be something it doesn't like about the the xml file I'm receiving. The file opens perfectly well in a browser. I had a little play with changing the "Details Level "1" tags making some of them Level "2" and so on but to no avail.

I've attached the original file which I receive from another application, over which I have no control, and a shortened version which works. Can you see why the original gives problems?
Thanks,
Jim.

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#15 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Using the XmlReader to read an xml file

Posted 18 February 2014 - 11:54 AM

Not an answer, but an observation from your last post: a browser isn't the best tool for viewing/editing XML. Text editors are better. Notice how in all your copy/pastes of the XML how you have dashes (" - ") inserted? That's because you copied from IE's XML Viewer. It lets you do things like collapse nodes, but it's actually parsing your XML instead of showing the text.

I suggest Notepad++, Notepad2, or just using Visual Studio to view the actual XML files.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2