XMLTextReader C#

2.2k views Asked by At
<myroot>
  some data.
</myroot>

I have an xml file with some data like above. I want to get all data coming between

 <myroot> and </myroot>

In to a string variable.

There is some restriction to me, that is i should use only XMLTextReader for this how can i do this just using XmlTextReader with out using xdocument

3

There are 3 answers

0
Coder On

you need a xmlnodelist and after that a foreach loop to go through the nodes. the xmlNode type has a innerHtml property. for ex: myxmlNode.SelectSingleNode("//REVNR").InnerText

0
Ademar On

Thats is a way to do it. Below a simple example on how to read xml in a very basic form: Im sure you create some logic with it

XmlTextReader reader = new XmlTextReader ("books.xml");

while (reader.Read()) 
{
    switch (reader.NodeType) 
    {
        case XmlNodeType.Element: // The node is an element.
            Console.Write("<" + reader.Name);
            Console.WriteLine(">");
            break;
        case XmlNodeType.Text: //Display the text in each element.
            Console.WriteLine (reader.Value);
            break;
        case XmlNodeType. EndElement: //Display the end of the element.
            Console.Write("</" + reader.Name);
        Console.WriteLine(">");
            break;
    }
}
0
Stefan On

If there are no child nodes in <myroot> then your choice is XmlReader.ReadElementContentAsString:

string content = reader.ReadElementContentAsString();

ReadElementContentAsString consumes the current node and advances the reader to the next element.

If there are any child nodes then it depends what you want to do. If you need the inner XML you should go for Adam's solution. If you need the content of the child nodes you have to recursively traverse the XML. To help you there, you need to explain what exactly you are trying to avchieve.