Current Node Position in XmlReader
The XmlReader class provides forward-only access to an XML stream or file. The current node is the XML node on which the reader is currently positioned. All methods called and actions taken are in relation to that current node, and all properties retrieved reflect the value of the current node.
The reader is advanced by calls to one of the Read methods. Repeatedly calling the Read method moves the reader to the next node. Such calls are typically performed inside a While loop.
The following example shows how you navigate through the stream to determine the current node type.
reader.MoveToContent(); // Parse the file and display each of the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("<{0}>", reader.Name); break; case XmlNodeType.Text: Console.Write(reader.Value); break; case XmlNodeType.CDATA: Console.Write("<![CDATA[{0}]]>", reader.Value); break; case XmlNodeType.ProcessingInstruction: Console.Write("<?{0} {1}?>", reader.Name, reader.Value); break; case XmlNodeType.Comment: Console.Write("<!--{0}-->", reader.Value); break; case XmlNodeType.XmlDeclaration: Console.Write("<?xml version='1.0'?>"); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value); break; case XmlNodeType.EntityReference: Console.Write(reader.Name); break; case XmlNodeType.EndElement: Console.Write("</{0}>", reader.Name); break; } }
The properties available in the XmlReader class are not applicable to every node type. For example, the IsEmptyElement property returns true if the current node is an element and ends with a forward slash character "/>". Calling this property on any other node type returns false because this property is not applicable to other node types. For a list of all the node types, see Types of XML Nodes.