Export (0) Print
Expand All

Reading Elements 

The following table describes the methods and properties that the XmlReader class provides for processing elements. After the XmlReader is positioned on an element, the node properties, such as Name, reflect the element values. In addition to the members described below, any of the general methods and properties of the XmlReader class can also be used to process elements. For example, you can use the ReadInnerXml method to read the contents of an element.

NoteNote

These methods include an initial call to the MoveToContent method.

Member name Description

IsStartElement

Checks if the current node is a start tag or an empty element tag.

ReadStartElement

Checks that the current node is an element and advances the reader to the next node.

ReadEndElement

Checks that the current node is an end tag and advances the reader to the next node.

ReadElementString

Reads a text-only element.

ReadToDescendant

Advances the XmlReader to the next descendant element with the specified name.

ReadToNextSibling

Advances the XmlReader to the next sibling element with the specified name.

IsEmptyElement

Checks if the current element has an empty element tag. This property enables you to determine the difference between the following:

  • <item num="123"/> (IsEmptyElement is true.)

  • <item num="123"> (IsEmptyElement is false, although element content is empty.)

In other words, IsEmptyElement simply reports whether or not the element in the source document has an end element tag.

Examples

The following code reads elements using the ReadStartElement and ReadString methods.

using (XmlReader reader = XmlReader.Create("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();

}

The following code processes elements by using a While loop.

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.
    }
  } 
} 

See Also

Community Additions

ADD
Show:
© 2014 Microsoft