public class XmlNodeReader : XmlReader
|
To read strongly typed data, use the XmlConvert class. For example, the following C# code reads in data and converts it from a String to a Double.
Double price = XmlConvert.ToDouble(reader.Value);
For further discussion on the XmlReader classes, see the conceptual topic at MSDN: readingxmlwithxmlreader.
ctor #1 | Creates an instance of the XmlNodeReader class using the specified XmlNode. |
AttributeCount | Read-only Overridden: Gets the number of attributes on the current node. |
BaseURI | Read-only Overridden: Gets the base URI of the current node. |
CanResolveEntity | Read-only Overridden: Gets a value indicating whether this reader can parse and resolve entities. |
Depth | Read-only Overridden: Gets the depth of the current node in the XML document. |
EOF | Read-only Overridden: Gets a value indicating whether the reader is positioned at the end of the stream. |
HasAttributes | Read-only Overridden: Gets a value indicating whether the current node has any attributes. |
HasValue | Read-only Overridden: Gets a value indicating whether the current node can have a XmlNodeReader.Value. |
IsDefault | Read-only Overridden: Gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema. |
IsEmptyElement | Read-only Overridden: Gets a value indicating whether the current node is an empty element (for example,
<MyElement/>
). |
Item | Read-only Overloaded: Item[int i] {get Overridden: Gets the value of the attribute with the specified index. |
Item | Read-only Overloaded: Item[string name] {get Overridden: Gets the value of the attribute with the specified name. |
Item | Read-only Overloaded: Item[string name, string namespaceURI] {get Overridden: Gets the value of the attribute with the specified local name and namespace URI. |
LocalName | Read-only Overridden: Gets the local name of the current node. |
Name | Read-only Overridden: Gets the qualified name of the current node. |
NamespaceURI | Read-only Overridden: Gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned. |
NameTable | Read-only Overridden: Gets the XmlNameTable associated with this implementation. |
NodeType | Read-only Overridden: Gets the type of the current node. |
Prefix | Read-only Overridden: Gets the namespace prefix associated with the current node. |
QuoteChar | Read-only Overridden: Gets the quotation mark character used to enclose the value of an attribute node. |
ReadState | Read-only Overridden: Gets the state of the reader. |
Value | Read-only Overridden: Gets the text value of the current node. |
XmlLang | Read-only Overridden: Gets the current xml:lang scope. |
XmlSpace | Read-only Overridden: Gets the current xml:space scope. |
Close | Overridden: Changes the XmlNodeReader.ReadState to Closed. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetAttribute | Overloaded:GetAttribute(int attributeIndex) Overridden: Gets the value of the attribute with the specified index. |
GetAttribute | Overloaded:GetAttribute(string name) Overridden: Gets the value of the attribute with the specified name. |
GetAttribute | Overloaded:GetAttribute(string name, string namespaceURI) Overridden: Gets the value of the attribute with the specified local name and namespace URI. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
IsStartElement (inherited from System.Xml.XmlReader) |
Overloaded:IsStartElement() See base class member description: System.Xml.XmlReader.IsStartElementCalls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag. |
IsStartElement (inherited from System.Xml.XmlReader) |
Overloaded:IsStartElement(string name) See base class member description: System.Xml.XmlReader.IsStartElementCalls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.Name property of the element found matches the given argument. |
IsStartElement (inherited from System.Xml.XmlReader) |
Overloaded:IsStartElement(string localname, string ns) See base class member description: System.Xml.XmlReader.IsStartElementCalls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found match the given strings. |
LookupNamespace | Overridden: Resolves a namespace prefix in the current element's scope. |
MoveToAttribute | Overloaded:MoveToAttribute(int attributeIndex) Overridden: Moves to the attribute with the specified index. |
MoveToAttribute | Overloaded:MoveToAttribute(string name) Overridden: Moves to the attribute with the specified name. |
MoveToAttribute | Overloaded:MoveToAttribute(string name, string namespaceURI) Overridden: Moves to the attribute with the specified local name and namespace URI. |
MoveToContent (inherited from System.Xml.XmlReader) |
See base class member description: System.Xml.XmlReader.MoveToContent Checks whether the current node is a content (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) node. If the node is not a content node, the reader skips ahead to the next content node or end of file. It skips over nodes of the following type: ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace. |
MoveToElement | Overridden: Moves to the element that contains the current attribute node. |
MoveToFirstAttribute | Overridden: Moves to the first attribute. |
MoveToNextAttribute | Overridden: Moves to the next attribute. |
Read | Overridden: Reads the next node from the stream. |
ReadAttributeValue | Overridden: Parses the attribute value into one or more Text, EntityReference, or EndEntity nodes. |
ReadElementString (inherited from System.Xml.XmlReader) |
Overloaded:ReadElementString() See base class member description: System.Xml.XmlReader.ReadElementStringReads a text-only element. |
ReadElementString (inherited from System.Xml.XmlReader) |
Overloaded:ReadElementString(string name) See base class member description: System.Xml.XmlReader.ReadElementStringChecks that the XmlReader.Name property of the element found matches the given string before reading a text-only element. |
ReadElementString (inherited from System.Xml.XmlReader) |
Overloaded:ReadElementString(string localname, string ns) See base class member description: System.Xml.XmlReader.ReadElementStringChecks that the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found matches the given strings before reading a text-only element. |
ReadEndElement (inherited from System.Xml.XmlReader) |
See base class member description: System.Xml.XmlReader.ReadEndElement Checks that the current content node is an end tag and advances the reader to the next node. |
ReadInnerXml | Overridden: Reads all the content, including markup, as a string. |
ReadOuterXml | Overridden: Reads the content, including markup, representing this node and all its children. |
ReadStartElement (inherited from System.Xml.XmlReader) |
Overloaded:ReadStartElement() See base class member description: System.Xml.XmlReader.ReadStartElementChecks that the current node is an element and advances the reader to the next node. |
ReadStartElement (inherited from System.Xml.XmlReader) |
Overloaded:ReadStartElement(string name) See base class member description: System.Xml.XmlReader.ReadStartElementChecks that the current content node is an element with the given XmlReader.Name and advances the reader to the next node. |
ReadStartElement (inherited from System.Xml.XmlReader) |
Overloaded:ReadStartElement(string localname, string ns) See base class member description: System.Xml.XmlReader.ReadStartElementChecks that the current content node is an element with the given XmlReader.LocalName and XmlReader.NamespaceURI and advances the reader to the next node. |
ReadString | Overridden: Reads the contents of an element or text node as a string. |
ResolveEntity | Overridden: Resolves the entity reference for EntityReference nodes. |
Skip | Overridden: Skips the children of the current node. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public XmlNodeReader( |
node
XmlDocument doc = new XmlDocument(); doc.Load("sample.xml"); XmlNodeReader reader = new XmlNodeReader(doc);
public override int AttributeCount {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the root element. reader.MoveToContent(); if (reader.HasAttributes){ for (int i=0; i<reader.AttributeCount; i++){ reader.MoveToAttribute(i); Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Return the reader to the book element. reader.MoveToElement(); } } finally { if (reader != null) reader.Close(); } } } // End class
public override string BaseURI {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load an XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load("http://localhost/uri.xml"); reader = new XmlNodeReader(doc); //Parse the file and display the base URI for each node. while (reader.Read()) { Console.WriteLine("({0}) {1}", reader.NodeType, reader.BaseURI); } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, uri.xml, as input. The style.xml file contains the XML text
<style>hardcover</style>
.<!-- XML fragment --> <!DOCTYPE book [<!ENTITY s SYSTEM "tmp/style.xml">]> <book genre="novel"> <title>Pride And Prejudice</title> <misc>&s;</misc> </book>
public override bool CanResolveEntity {get;}
|
public override int Depth {get;}
|
public override bool EOF {get;}
|
public override bool HasAttributes {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the root element. reader.MoveToContent(); if (reader.HasAttributes){ for (int i=0; i<reader.AttributeCount; i++){ reader.MoveToAttribute(i); Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Return the reader to the book element. reader.MoveToElement(); } } finally { if (reader != null) reader.Close(); } } } // End class
public override bool HasValue {get;}
|
Node Type | Value |
---|---|
Attribute | The value of the attribute. |
CDATA | The content of the CDATA section. |
Comment | The content of the comment. |
DocumentType | The internal subset. |
ProcessingInstruction | The entire content, excluding the target. |
SignificantWhitespace | The white space between markup in a mixed content model. |
Text | The content of the text node. |
Whitespace | The white space between markup. |
XmlDeclaration | The content of the declaration. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load an XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version='1.0' ?>" + "<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book>" + "<title>Pride And Prejudice</title>" + "<misc>&h;</misc>" + "</book>"); reader = new XmlNodeReader(doc); //Parse the file and display each node. while (reader.Read()) { if (reader.HasValue) Console.WriteLine("({0}) {1}={2}", reader.NodeType, reader.Name, reader.Value); else Console.WriteLine("({0}) {1}", reader.NodeType, reader.Name); } } finally { if (reader!=null) reader.Close(); } } } // End class
public override bool IsDefault {get;}
|
<MyElement/>
).
public override bool IsEmptyElement {get;}
|
<item bar="123"/>
(IsEmptyElement is true).
<item bar="123">
(IsEmptyElement is false).
A corresponding EndElement node is not generated for empty elements.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "<misc/>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Parse the XML and display the text content of each of the elements. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.IsEmptyElement) Console.WriteLine("<{0}/>", reader.Name); else{ Console.Write("<{0}> ", reader.Name); reader.Read(); //Read the start tag. if (reader.IsStartElement()) //Handle nested elements. Console.Write("\r\n<{0}>", reader.Name); Console.WriteLine(reader.ReadString()); //Read the text content of the element. } } } } finally { if (reader != null) reader.Close(); } } } // End class
public override string this[int i] {get;}
|
i
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | The i parameter is less than 0 or greater than or equal to XmlNodeReader.AttributeCount. |
public override string this[string name] {get;}
|
name
reader["PUBLIC"]
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); // Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the ISBN attribute. reader.MoveToContent(); string isbn =reader["ISBN"]; Console.WriteLine("The ISBN value: " + isbn); } finally { if (reader != null) reader.Close(); } } } // End class
public override string this[string name, string namespaceURI] {get;}
|
name
namespaceURI
public override string LocalName {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples'> " + "<title>Pride And Prejudice</title>" + "<bk:genre>novel</bk:genre>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Parse the XML. If they exist, display the prefix and //namespace URI of each node. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.Prefix==String.Empty) Console.WriteLine("<{0}>", reader.LocalName); else{ Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName); Console.WriteLine(" The namespace URI is " + reader.NamespaceURI); } } } } finally { if (reader != null) reader.Close(); } } } // End class
public override string Name {get;}
|
using System; using System.IO; using System.Xml; public class Sample { private const String filename = "items.xml"; public static void Main() { XmlNodeReader reader = null; try { //Create an XmlNodeReader to read the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //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(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.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, items.xml, as input.
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with a char entity: A</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>
public override string NamespaceURI {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples'> " + "<title>Pride And Prejudice</title>" + "<bk:genre>novel</bk:genre>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Parse the XML. If they exist, display the prefix and //namespace URI of each node. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.Prefix==String.Empty) Console.WriteLine("<{0}>", reader.LocalName); else{ Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName); Console.WriteLine(" The namespace URI is " + reader.NamespaceURI); } } } } finally { if (reader != null) reader.Close(); } } } // End class
public override XmlNameTable NameTable {get;}
|
public override XmlNodeType NodeType {get;}
|
using System; using System.IO; using System.Xml; public class Sample { private const String filename = "items.xml"; public static void Main() { XmlNodeReader reader = null; try { //Create an XmlNodeReader to read the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //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(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.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, items.xml, as input.
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with a char entity: A</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>
public override string Prefix {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples'> " + "<title>Pride And Prejudice</title>" + "<bk:genre>novel</bk:genre>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Parse the XML. If they exist, display the prefix and //namespace URI of each node. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.Prefix==String.Empty) Console.WriteLine("<{0}>", reader.LocalName); else{ Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName); Console.WriteLine(" The namespace URI is " + reader.NamespaceURI); } } } } finally { if (reader != null) reader.Close(); } } } // End class
public override char QuoteChar {get;}
|
public override ReadState ReadState {get;}
|
public override string Value {get;}
|
using System; using System.IO; using System.Xml; public class Sample { private const String filename = "items.xml"; public static void Main() { XmlNodeReader reader = null; try { //Create an XmlNodeReader to read the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //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(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.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, items.xml, as input.
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with a char entity: A</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>
public override string XmlLang {get;}
|
<root xml:lang="en-us">
<name>Fred</name>
</root>
When the reader is positioned on the name element, you can use this property to find that it is in the scope of a US English xml:lang attribute.
The string returned is also in XmlNodeReader.NameTable.
public override XmlSpace XmlSpace {get;}
|
public override void Close(); |
using System; using System.IO; using System.Xml; public class Sample { private const String filename = "items.xml"; public static void Main() { XmlNodeReader reader = null; try { //Create an XmlNodeReader to read the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //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(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.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, items.xml, as input.
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with a char entity: A</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>
~XmlNodeReader(); |
attributeIndex
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | The i parameter is less than 0 or greater than or equal to XmlNodeReader.AttributeCount. |
name
If the reader is positioned on a DocumentType node, this method can be used to get the PUBLIC and SYSTEM literals, for example,
reader.GetAttribute("PUBLIC")
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); // Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the ISBN attribute. reader.MoveToContent(); string isbn = reader.GetAttribute("ISBN"); Console.WriteLine("The ISBN value: " + isbn); } finally { if (reader != null) reader.Close(); } } } // End class
name
namespaceURI
<test xmlns:dt="urn:datatypes" dt:type="int"/>
You can lookup the dt:type attribute using one argument (prefix and local name) or two arguments (local name and namespace URI):
String dt = reader.GetAttribute("dt:type");
String dt2 = reader.GetAttribute("type","urn:datatypes");
To lookup the xmlns:dt attribute, use one of the following arguments:
String dt3 = reader.GetAttribute("xmlns:dt");
String dt4 = reader.GetAttribute("dt",http://www.w3.org/2000/xmlns/);
You can also get this information using the XmlNodeReader.Prefix property.
public virtual int GetHashCode(); |
public Type GetType(); |
public virtual bool IsStartElement(); |
Exception Type | Condition |
---|---|
XmlException | Incorrect XML is encountered in the input stream. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlTextReader reader = null; try { //Load the reader with the XML file. reader = new XmlTextReader("elems.xml"); //Parse the XML and display the text content of each of the elements. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.IsEmptyElement) Console.WriteLine("<{0}/>", reader.Name); else{ Console.Write("<{0}> ", reader.Name); reader.Read(); //Read the start tag. if (reader.IsStartElement()) //Handle nested elements. Console.Write("\r\n<{0}>", reader.Name); Console.WriteLine(reader.ReadString()); //Read the text content of the element. } } } } finally { if (reader != null) reader.Close(); } } } // End classThe example uses the file, elems.xml, as input.
<book> <title>Pride And Prejudice</title> <price>19.95</price> <misc/> </book>
name
Exception Type | Condition |
---|---|
XmlException | Incorrect XML is encountered in the input stream. |
localname
ns
Exception Type | Condition |
---|---|
XmlException | Incorrect XML is encountered in the input stream. |
prefix
<root xmlns:a="urn:456"> <item> <ref href="a:b"/> </item> </root>In the preceding XML, if the reader is positioned on the href attribute, the prefix
a
is resolved by calling
reader.LookupNamesapce("a")
. The returned string is
urn:456
.
protected object MemberwiseClone(); |
public override void MoveToAttribute( |
attributeIndex
Exception Type | Condition |
---|---|
ArgumentOutOfRangeException | The i parameter is less than 0 or greater than or equal to XmlReader.AttributeCount. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the root element. reader.MoveToContent(); if (reader.HasAttributes){ for (int i=0; i<reader.AttributeCount; i++){ reader.MoveToAttribute(i); Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Return the reader to the book element. reader.MoveToElement(); } } finally { if (reader != null) reader.Close(); } } } // End class
name
name
namespaceURI
public virtual XmlNodeType MoveToContent(); |
Exception Type | Condition |
---|---|
XmlException | Incorrect XML encountered in the input stream. |
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "price") { _price = reader.ReadString(); }
This code can handle the following inputs without breaking:
<price>123.4</price>
and
<?xml version="1.0"><!DOCTYPE price SYSTEM
"abc"><price>123.4</price>
and
<?xml version="1.0"><!DOCTYPE price SYSTEM "abc"
[<!ENTTIY p
"123.4">]><price>&p;</price>
and
<!-- some test comment --><?processing
instruction?><price>123.4</price>
public override bool MoveToElement(); |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the root element. reader.MoveToContent(); if (reader.HasAttributes){ for (int i=0; i<reader.AttributeCount; i++){ reader.MoveToAttribute(i); Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Return the reader to the book element. reader.MoveToElement(); } } finally { if (reader != null) reader.Close(); } } } // End class
public override bool MoveToFirstAttribute(); |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the genre attribute. reader.MoveToContent(); reader.MoveToFirstAttribute(); string genre=reader.Value; Console.WriteLine("The genre value: " + genre); } finally { if (reader != null) reader.Close(); } } } // End class
public override bool MoveToNextAttribute(); |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78'> " + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the book element. reader.MoveToContent(); while (reader.MoveToNextAttribute()) { Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Move the reader to the title element. reader.Read(); //Read the title and price elements. Console.WriteLine(reader.ReadElementString()); Console.WriteLine(reader.ReadElementString()); } finally { if (reader != null) reader.Close(); } } } // End class
public override bool Read(); |
using System; using System.IO; using System.Xml; public class Sample { private const String filename = "items.xml"; public static void Main() { XmlNodeReader reader = null; try { //Create an XmlNodeReader to read the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //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(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.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, items.xml, as input.
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with a char entity: A</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>
public override bool ReadAttributeValue(); |
false if the reader is not positioned on an attribute node when the initial call is made or if all the attribute values have been read.
An empty attribute, such as,
misc=""
, returns true with a single node with a value of String.Empty.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load an XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'harcover'>]>" + "<book genre='novel' misc='sale-item &h; 1987'>" + "</book>"); //Create the reader. reader = new XmlNodeReader(doc); //Read the misc attribute. The attribute is parsed into multiple //text and entity reference nodes. reader.MoveToContent(); reader.MoveToAttribute("misc"); while (reader.ReadAttributeValue()){ if (reader.NodeType==XmlNodeType.EntityReference) //To expand the entity, call ResolveEntity. Console.WriteLine("{0} {1}", reader.NodeType, reader.Name); else Console.WriteLine("{0} {1}", reader.NodeType, reader.Value); } } finally { if (reader != null) reader.Close(); } } } // End class
public virtual string ReadElementString(); |
<item></item>
or
<item/>
).Exception Type | Condition |
---|---|
XmlException | The next content node is not a start tag; or the element found does not contain a simple text value. |
Using the XML,
<name>Arlene Huff</name>
, ReadElementString consumes the element and returns the string Arlene Huff.
This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.
using System; using System.IO; using System.Xml; //Reads an XML fragment public class Sample { private const String filename = "book.xml"; public static void Main() { XmlTextReader reader = null; try { //Load the file and ignore all whitespace. reader = new XmlTextReader(filename); reader.WhitespaceHandling = WhitespaceHandling.None; //Moves the reader to the root element. reader.MoveToContent(); //Read the title and price elements. Console.WriteLine("Content of the title element: {0}", reader.ReadElementString()); Console.WriteLine("Content of the price element: {0}", reader.ReadElementString());; } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the data file book.xml:
<!--sample XML fragment--> <book genre='novel' ISBN='1-861003-78' misc='sale-item'> <title>The Handmaid's Tale</title> <price>14.95</price> </book>
name
<item></item>
or
<item/>
).Exception Type | Condition |
---|---|
XmlException | If the next content node is not a start tag; if the element Name does not match the given argument; or if the element found does not contain a simple text value. |
Using the XML,
<name>Arlene
Huff</name>
, ReadElementString consumes the element and returns the string Arlene Huff.
This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.
localname
ns
<item></item>
or
<item/>
).Exception Type | Condition |
---|---|
XmlException | If the next content node is not a start tag; if the element LocalName or NamespaceURI do not match the given arguments; or if the element found does not contain a simple text value. |
Using the XML,
<name>Arlene
Huff</name>
, ReadElementString consumes the element and returns the string Arlene Huff.
This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.
public virtual void ReadEndElement(); |
Exception Type | Condition |
---|---|
XmlException | The current node is not an end tag or if incorrect XML is encountered in the input stream. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the reader. XmlTextReader reader = new XmlTextReader("book3.xml"); //Parse the XML document. ReadString is used to //read the text content of the elements. reader.Read(); reader.ReadStartElement("book"); reader.ReadStartElement("title"); Console.Write("The content of the title element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadStartElement("price"); Console.Write("The content of the price element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadEndElement(); //Close the reader. reader.Close(); } } // End classThe example uses the file, book3.xml, as input.
<book> <title>Pride And Prejudice</title> <price>19.95</price> </book>
public override string ReadInnerXml(); |
If the current node is neither an element nor attribute, an empty string is returned.
<node> this <child id="123"/> </node>
ReadInnerXml returns
this <child id="123"/>
This method handles element and attribute nodes in the following way:
Node Type | Child Content | Return Value | Position After the Call |
---|---|---|---|
Element | <item>text</item> | text | After the end tag. |
Attribute | <item attr1="val1" attr2="val2">text</item> | val1 | Remains on the attribute node attr1 . |
If the reader is positioned on a leaf node, calling ReadInnerXml is equivalent to calling XmlNodeReader.Read.
This method also checks for well-formed XML.
using System; using System.IO; using System.Xml; //Reads an XML fragment public class Sample { private const String filename = "2books.xml"; public static void Main() { XmlNodeReader reader = null; try { XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //Moves the reader to the root element. reader.MoveToContent(); //Moves the reader to the 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("\r\nRead the second book using ReadOuterXml..."); Console.WriteLine(reader.ReadOuterXml()); } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, 2books.xml, 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>
public override string ReadOuterXml(); |
This method handles element and attribute nodes in the following manner:
Node Type | Child Content | Return Value | Position After the Call |
---|---|---|---|
Element | <item>text</item> | <item>text</item> | After the end tag. |
Attribute | <item attr1="val1" attr2="val2">text</item> | attr="val1" | Remains on the attribute node attr1 . |
If the reader is positioned on a leaf node, calling ReadOuterXml is equivalent to calling XmlNodeReader.Read.
This method also checks for well-formed XML.
using System; using System.IO; using System.Xml; //Reads an XML fragment public class Sample { private const String filename = "2books.xml"; public static void Main() { XmlNodeReader reader = null; try { XmlDocument doc = new XmlDocument(); doc.Load(filename); reader = new XmlNodeReader(doc); //Moves the reader to the root element. reader.MoveToContent(); //Moves the reader to the 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("\r\nRead the second book using ReadOuterXml..."); Console.WriteLine(reader.ReadOuterXml()); } finally { if (reader!=null) reader.Close(); } } } // End classThe example uses the file, 2books.xml, 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>
public virtual void ReadStartElement(); |
Exception Type | Condition |
---|---|
XmlException | XmlReader.IsStartElement returns false. |
public virtual void ReadStartElement( |
name
Exception Type | Condition |
---|---|
XmlException | XmlReader.IsStartElement returns false or if the XmlReader.Name of the element does not match the given name. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the reader. XmlTextReader reader = new XmlTextReader("book3.xml"); //Parse the XML document. ReadString is used to //read the text content of the elements. reader.Read(); reader.ReadStartElement("book"); reader.ReadStartElement("title"); Console.Write("The content of the title element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadStartElement("price"); Console.Write("The content of the price element: "); Console.WriteLine(reader.ReadString()); reader.ReadEndElement(); reader.ReadEndElement(); //Close the reader. reader.Close(); } } // End classThe example uses the file, book3.xml, as input.
<book> <title>Pride And Prejudice</title> <price>19.95</price> </book>
localname
ns
Exception Type | Condition |
---|---|
XmlException | XmlReader.IsStartElement returns false, or the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found do not match the given arguments. |
public override string ReadString(); |
Note: The text node can be either an element or an attribute text node.
If positioned on a text-like node, ReadString performs the same concatenation from the text node to the element end tag. If the reader is positioned on an attribute text node, ReadString has the same functionality as if the reader were position on the element start tag. It returns all the concatenated element text nodes.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "<misc/>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Parse the XML and display the text content of each of the elements. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.IsEmptyElement) Console.WriteLine("<{0}/>", reader.Name); else{ Console.Write("<{0}> ", reader.Name); reader.Read(); //Read the start tag. if (reader.IsStartElement()) //Handle nested elements. Console.Write("\r\n<{0}>", reader.Name); Console.WriteLine(reader.ReadString()); //Read the text content of the element. } } } } finally { if (reader != null) reader.Close(); } } } // End class
public override void ResolveEntity(); |
Exception Type | Condition |
---|---|
InvalidOperationException | The reader is not positioned on an EntityReference node. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load an XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book>" + "<title>Pride And Prejudice</title>" + "<misc>&h;</misc>" + "</book>"); //Create the reader. reader = new XmlNodeReader(doc); reader.MoveToContent(); //Move to the root element. reader.Read(); //Move to title start tag. reader.Skip(); //Skip the title element. //Read the misc start tag. The reader is now positioned on //the entity reference node. reader.ReadStartElement(); //You must call ResolveEntity to expand the entity reference. //The entity replacement text is then parsed and returned as a child node. Console.WriteLine("Expand the entity..."); reader.ResolveEntity(); Console.WriteLine("The entity replacement text is returned as a text node."); reader.Read(); Console.WriteLine("NodeType: {0} Value: {1}", reader.NodeType ,reader.Value); Console.WriteLine("An EndEntity node closes the entity reference scope."); reader.Read(); Console.WriteLine("NodeType: {0} Name: {1}", reader.NodeType,reader.Name); } finally { if (reader != null) reader.Close(); } } }
public override void Skip(); |
<a name="bob" age="123"> <x/>abc<y/> </a> <b> ... </b>
If the reader is positioned on the "<a>" node or any of its attributes, calling Skip positions the reader to the "<b>" node.
If the reader is positioned on a leaf node already (such as element "x" or the text node "abc"), calling Skip is the same as calling XmlNodeReader.Read.
This method checks for well-formed XML.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!-- sample XML -->" + "<book>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); reader.MoveToContent(); //Move to the book node. reader.Read(); //Read the book start tag. reader.Skip(); //Skip the title element. Console.WriteLine(reader.ReadOuterXml()); //Read the price element. } finally { if (reader != null) reader.Close(); } } } // End class
public virtual string ToString(); |