How to output XML as a string from an XmlTextReader? Options

codeling Posts: 1057 Points: 4443
Posted: Tuesday, February 12, 2019 3:42:12 PM

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.
  // Moves to book node.

  // 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...");

  // 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...");


The example uses 2books.xml file as input.

<!--sample XML fragment-->
  <book genre='novel' ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
  <book genre='novel' ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>
Users browsing this topic