public abstract class XmlReader
|
XmlReader conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations and is implemented in the following classes:
Class | Description |
---|---|
XmlTextReader | Fastest implementation of XmlReader . It checks for well-formed XML, but does not support data validation. This reader cannot expand general entities and does not support default attributes. |
XmlValidatingReader | Implementation of XmlReader that can validate data using DTDs or schemas. This reader can also expand general entities and supports default attributes. |
XmlNodeReader | Implementation of XmlReader that reads XML data from an XmlNode . |
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);
XmlReader throws an XmlException on XML parse errors. After an exception is thrown the state of the reader is not predictable. For example, the reported node type may be different than the actual node type of the current node.
For further discussion on the XmlReader classes, see the conceptual topic at MSDN: readingxmlwithxmlreader.
AttributeCount | Read-only When overridden in a derived class, gets the number of attributes on the current node. |
BaseURI | Read-only When overridden in a derived class, gets the base URI of the current node. |
CanResolveEntity | Read-only Gets a value indicating whether this reader can parse and resolve entities. |
Depth | Read-only When overridden in a derived class, gets the depth of the current node in the XML document. |
EOF | Read-only When overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream. |
HasAttributes | Read-only Gets a value indicating whether the current node has any attributes. |
HasValue | Read-only When overridden in a derived class, gets a value indicating whether the current node can have a XmlReader.Value. |
IsDefault | Read-only When overridden in a derived class, 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 When overridden in a derived class, gets a value indicating whether the current node is an empty element (for example,
<MyElement/>
). |
Item | Read-only Overloaded: Item[int i] {get When overridden in a derived class, gets the value of the attribute with the specified index. |
Item | Read-only Overloaded: Item[string name] {get When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name. |
Item | Read-only Overloaded: Item[string name, string namespaceURI] {get When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI. |
LocalName | Read-only When overridden in a derived class, gets the local name of the current node. |
Name | Read-only When overridden in a derived class, gets the qualified name of the current node. |
NamespaceURI | Read-only When overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned. |
NameTable | Read-only When overridden in a derived class, gets the XmlNameTable associated with this implementation. |
NodeType | Read-only When overridden in a derived class, gets the type of the current node. |
Prefix | Read-only When overridden in a derived class, gets the namespace prefix associated with the current node. |
QuoteChar | Read-only When overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node. |
ReadState | Read-only When overridden in a derived class, gets the state of the reader. |
Value | Read-only When overridden in a derived class, gets the text value of the current node. |
XmlLang | Read-only When overridden in a derived class, gets the current xml:lang scope. |
XmlSpace | Read-only When overridden in a derived class, gets the current xml:space scope. |
Close | When overridden in a derived class, changes the XmlReader.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 i) When overridden in a derived class, gets the value of the attribute with the specified index. |
GetAttribute | Overloaded:GetAttribute(string name) When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name. |
GetAttribute | Overloaded:GetAttribute(string name, string namespaceURI) When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI. |
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. |
IsName | Gets a value indicating whether the string argument is a valid XML name. |
IsNameToken | Gets a value indicating whether or not the string argument is a valid XML name token. |
IsStartElement | Overloaded:IsStartElement() Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag. |
IsStartElement | Overloaded:IsStartElement(string name) Calls 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 | Overloaded:IsStartElement(string localname, string ns) Calls 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 | When overridden in a derived class, resolves a namespace prefix in the current element's scope. |
MoveToAttribute | Overloaded:MoveToAttribute(int i) When overridden in a derived class, moves to the attribute with the specified index. |
MoveToAttribute | Overloaded:MoveToAttribute(string name) When overridden in a derived class, moves to the attribute with the specified XmlReader.Name. |
MoveToAttribute | Overloaded:MoveToAttribute(string name, string ns) When overridden in a derived class, moves to the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI. |
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 | When overridden in a derived class, moves to the element that contains the current attribute node. |
MoveToFirstAttribute | When overridden in a derived class, moves to the first attribute. |
MoveToNextAttribute | When overridden in a derived class, moves to the next attribute. |
Read | When overridden in a derived class, reads the next node from the stream. |
ReadAttributeValue | When overridden in a derived class, parses the attribute value into one or more Text, EntityReference, or EndEntity nodes. |
ReadElementString | Overloaded:ReadElementString() Reads a text-only element. |
ReadElementString | Overloaded:ReadElementString(string name) Checks that the XmlReader.Name property of the element found matches the given string before reading a text-only element. |
ReadElementString | Overloaded:ReadElementString(string localname, string ns) Checks that the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found matches the given strings before reading a text-only element. |
ReadEndElement | Checks that the current content node is an end tag and advances the reader to the next node. |
ReadInnerXml | When overridden in a derived class, reads all the content, including markup, as a string. |
ReadOuterXml | When overridden in a derived class, reads the content, including markup, representing this node and all its children. |
ReadStartElement | Overloaded:ReadStartElement() Checks that the current node is an element and advances the reader to the next node. |
ReadStartElement | Overloaded:ReadStartElement(string name) Checks that the current content node is an element with the given XmlReader.Name and advances the reader to the next node. |
ReadStartElement | Overloaded:ReadStartElement(string localname, string ns) Checks 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 | When overridden in a derived class, reads the contents of an element or text node as a string. |
ResolveEntity | When overridden in a derived class, resolves the entity reference for EntityReference nodes. |
Skip | 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. |
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. |
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:
protected XmlReader(); |
public abstract int AttributeCount {get;}
|
public abstract string BaseURI {get;}
|
public virtual bool CanResolveEntity {get;}
|
public abstract int Depth {get;}
|
public abstract bool EOF {get;}
|
public virtual bool HasAttributes {get;}
|
public void DisplayAttributes(XmlReader reader) { if (reader.HasAttributes) { Console.WriteLine("Attributes of <" + reader.Name + ">"); while (reader.MoveToNextAttribute()) { Console.WriteLine(" {0}={1}", reader.Name, reader.Value); } } }
public abstract 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. |
public abstract bool IsDefault {get;}
|
<MyElement/>
).
public abstract 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.
public abstract string this[int i] {get;}
|
i
public abstract string this[string name] {get;}
|
name
reader["PUBLIC"]
public abstract string this[string name, string namespaceURI] {get;}
|
name
namespaceURI
public abstract string LocalName {get;}
|
public abstract string Name {get;}
|
public abstract string NamespaceURI {get;}
|
public abstract XmlNameTable NameTable {get;}
|
public abstract XmlNodeType NodeType {get;}
|
public abstract string Prefix {get;}
|
public abstract char QuoteChar {get;}
|
public abstract ReadState ReadState {get;}
|
public abstract string Value {get;}
|
public abstract 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 XmlReader.NameTable.
public abstract XmlSpace XmlSpace {get;}
|
public abstract void Close(); |
~XmlReader(); |
i
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")
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 XmlReader.Prefix property.
public virtual int GetHashCode(); |
public Type GetType(); |
str
str
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 abstract void MoveToAttribute( |
i
name
name
ns
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 abstract bool MoveToElement(); |
public abstract bool MoveToFirstAttribute(); |
public abstract bool MoveToNextAttribute(); |
public abstract bool Read(); |
Exception Type | Condition |
---|---|
XmlException | An error occurred while parsing the XML. |
public abstract 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.
Implementations of XmlReader that cannot expand general entities return the general entities as a single empty( XmlReader.Value is String.Empty) EntityReference node.
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 abstract string ReadInnerXml(); |
If the current node is neither an element nor attribute, an empty string is returned.
Exception Type | Condition |
---|---|
XmlException | The XML was not well-formed, or an error occurred while parsing the XML. |
<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 XmlReader.Read.
This method also checks for well-formed XML.
public abstract string ReadOuterXml(); |
Exception Type | Condition |
---|---|
XmlException | The XML was not well-formed, or an error occurred while parsing the XML. |
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 XmlReader.Read.
This method also checks for well-formed XML.
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 abstract string ReadString(); |
Note: The text node can be either an element or an attribute text node.
Exception Type | Condition |
---|---|
XmlException | An error occurred while parsing the XML. |
If positioned on a text 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.
public abstract void ResolveEntity(); |
Exception Type | Condition |
---|---|
InvalidOperationException | The reader is not positioned on an EntityReference node; this implementation of the reader cannot resolve entities ( XmlReader.CanResolveEntity returns false). |
public virtual void Skip(); |
<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 the
<x>
node or the text node
abc
), calling Skip is the same as calling XmlReader.Read.
<a name="bob" age="123"> <x/>abc<y/> </a> <b> ... </b>
This method checks for well-formed XML.
If the reader is an XmlValidatingReader, this method also validates the skipped content.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlTextReader reader = null; try { //Load the XmlTextReader reader = new XmlTextReader("2books.xml"); reader.WhitespaceHandling = WhitespaceHandling.None; //Move the reader to the second book node. reader.MoveToContent(); reader.Read(); reader.Skip(); //Skip the first book. //Parse the file starting with the second book node. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("<{0}", reader.Name); while (reader.MoveToNextAttribute()){ Console.Write(" {0}='{1}'", reader.Name, reader.Value); } Console.Write(">"); break; case XmlNodeType.Text: Console.Write(reader.Value); break; case XmlNodeType.EndElement: Console.Write("</{0}>", reader.Name); break; } } } 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 string ToString(); |