Reading XML Fragments with the XmlTextReader

The XmlTextReader class can read XML fragments by parsing a string as a fragment of XML. Because the data in the string is assumed to be a fragment, the root level rules for well-formed XML documents are not applied. The following XmlTextReader constructor methods are the prototypes that take a string or stream fragment.

Public Sub New(xmlFragment As String, ByVal fragType As XmlNodeType, _
   ByVal content As XmlParserContext)
Public Sub New(ByVal xmlFragment as Stream, _
ByVal fragType as XmlNodeType, ByVal context As XmlParserContext)
[C#]
public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext context);
public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context);

If Encoding property of the context is null, the stream must have a byte order mark at the beginning. If it does not, it is assumed that the stream is UTF-8.

The second parameter, the XmlNodeType, determines how the given string is parsed. The following table lists the node type, and what type of data the parser expects.

Node type Fragment contains
Element Any valid element content, including a combination of elements, comments, processing instructions, CDATA, and text.
Attribute The value of an attribute.
Document The contents of an entire XML document. This type enforces the root level rules.

Passing in any other XmlNodeTypes throws an ArgumentException.

This XmlParserContext class provides all the required information needed to start an XML parser up at any random point within an XML document. For the XmlTextReader, the XmlParserContext is used to provide information such as the XmlNameTable to use, the namespace scope, and the current xml:lang and the xml:space scope.

Example

The following example uses the XmlTextReader to read XML fragments and write them to the console.

Dim tr As New XmlTextReader("<element1> abc </element1>  <element2> qrt </element2> <?pi asldfjsd ?> <!-- comment -->", XmlNodeType.Element, Nothing)
While tr.Read()
    Console.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name) 
End While       
[C#]
XmlTextReader tr = new XmlTextReader("<element1> abc </element1> 
  <element2> qrt </element2>
  <?pi asldfjsd ?>
  <!-- comment -->", XmlNodeType.Element, null);
while(tr.Read())
    Console.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
    }

For a code example that show how to read an XML fragment and use the XmlParserContext to supply the namespace from an XmlNamespaceManager, see Reading XML Fragments with the XmlValidatingReader.

See Also

Reading XML Data with XmlTextReader