web analytics

How to output XML as a string from an XmlTextReader?

Options

codeling 1595 - 6639
@2019-02-12 15:42:12

The following C# code shows you how to output XML as a string from an XmlTextReader by calling the ReadInnerXml and ReadOuterXml methods.

// Load the file and ignore all white space.
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;

//MemoryStream = new MemoryStream(bytXML, 0, bytXML.Length);
//using (XmlReader reader = XmlReader.Create(memoryStream))

using (XmlReader reader = XmlReader.Create("2books.xml")) {

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

  // Note that ReadInnerXml only returns the markup of the node's children
  // so the book's attributes are not returned.
  Console.WriteLine("Read the first book using ReadInnerXml...");
  Console.WriteLine(reader.ReadInnerXml());

  // ReadOuterXml returns the markup for the current node and its children
  // so the book's attributes are also returned.
  Console.WriteLine("Read the second book using ReadOuterXml...");
  Console.WriteLine(reader.ReadOuterXml());      

}

The example uses 2books.xml file as input.

<!--sample XML fragment-->
<bookstore>
  <book genre='novel' ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <book genre='novel' ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
</bookstore>

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com