
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
834
|
Chapter 15: XML
ELEMENT: Node3
ATTRIBUTE: nodeId='3'
TEXT: Third Node
Discussion
Reading existing XML and identifying different node types is one of the fundamental
actions that you will need to perform when dealing with XML. The code in the Solu-
tion creates an
XmlReader from a string (it could also have used a stream), then iter-
ates over the nodes while re-creating the formatted XML for output to the console
window.
The Solution shows creating a
MemoryStream from an XML fragment in a string like
this:
string xmlFragment = "<?xml version='1.0'?>" +
"<!-- My sample XML -->" +
"<?pi myProcessingInstruction?>" +
"<Root>" +
"<Node1 nodeId='1'>First Node</Node1>" +
"<Node2 nodeId='2'>Second Node</Node2>" +
"<Node3 nodeId='3'>Third Node</Node3>" +
"</Root>";
byte[] bytes = Encoding.UTF8.GetBytes(xmlFragment);
MemoryStream memStream = new MemoryStream(bytes);
Once the MemoryStream has been established, the settings for the XmlReader need to be
set up on an
XmlReaderSettings object instance. These settings tell the XmlReader to
check for any illegal characters in the XML fragment:
XmlReaderSettings settings = new XmlReaderSettings( );
// Check for any illegal characters in the XML.
settings.CheckCharacters = true;
The while loop iterates over the XML by reading one node at a time