1

Whats wrong with my code?

        XmlTextReader textReader = new XmlTextReader(@"D:\xml_file.xml");
        textReader.Read();

        // If the node has value

        while (textReader.Read())
        {
            // Move to fist element

            textReader.MoveToElement();
            Console.WriteLine("XmlTextReader Properties Test");
            Console.WriteLine("===================");
            // Read this element's properties and display them on console
            Console.WriteLine("id:" + textReader.id.ToString());
            Console.WriteLine("name:" + textReader.name.ToString());
            Console.WriteLine("time:" + textReader.time.ToString());
        }
        Console.ReadLine()

show erron on: id, name, time

My XML file:

<students>
 <student>
  <id>1</id>
  <name>Rikko Nora</name>
  <time>2010-03-12</time>
 </student>
 <student>
  <id>2</id>
  <name>Rikko Nora2</name>
  <time>2010-05-15</time>
 </student>
</students>
0

2 Answers 2

6

The XmlTextReader does not adapt itself to the shape of the XML that you are reading. The compilation error that you are getting lies with these lines:

Console.WriteLine("id:" + textReader.id.ToString());
Console.WriteLine("name:" + textReader.name.ToString());
Console.WriteLine("time:" + textReader.time.ToString());

The XmlTextReader class does not have id, name, and time properties.

Rather, when you use the XmlTextReader, after you move to a node, you will want to use the ReadContentAs{ContentType} methods to read the element content as a particular type instance.

If you are looking to read object representations from XML then you might want to take a look at XML Serialization in the .NET Framework.

Sign up to request clarification or add additional context in comments.

Comments

1

Try using the new XDocument class to load the XML and than run Linq queries on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.