Xml and ReadElementString

T

Tony Johansson

Hello!

Below is some code and the xml file that I use.

If I examine the reader variable before row marked with 1 is executed we
have the following contents in the reader variable {Element,Name="book"}

What I don't fully understand is why ReadElementString() write out at 1 "The
Handmaid's Tale"
when the reader contains book. I would understand it if reader had been
title.

Can somebode explain that ?

//main
{
//Load the file and ignore all whitespace.
XmlTextReader reader = new XmlTextReader("test.xml");
reader.WhitespaceHandling = WhitespaceHandling.None;

//Moves the reader to the root element.
reader.MoveToContent();

//Read the title and price elements.
1 Console.WriteLine("Content of the title element: {0}",
reader.ReadElementString());
Console.WriteLine("Content of the price element: {0}",
reader.ReadElementString());
}

<?xml version="1.0" encoding="utf-8" ?>
<book>
<title>The Handmaid's Tale</title>
<price>14.95</price>
</book>

//Tony
 
T

Tony Johansson

Hello!

In your answer below you mentioned whitespace.
I just wonder what do you mean by that?
When you call ReadElementString(), here's what happens:

- it calls MoveToContent() to ensure it's starting at a "content" node
(pretty much anything except a comment, processing instruction, doctype,
or whitespace). for this example input, that call doesn't do anything
(you've already called MoveToContent(), so you're already there)
- it then calls Read() to consume the element start node. for this
example input, this causes the reader to be positioned such that the next
node is the "title" element
- it then calls ReadString() to get the string from the current element,
which is the "title" element

//Tony
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top