This documentation is archived and is not being maintained.

Reading XML Fragments with the XmlTextReader

The XmlTextReader class can read XML fragments by parsing a string as a fragment of XML.


In the .NET Framework version 2.0, the recommended practice is to create XmlReader instances using the XmlReaderSettings class and the Create method. This allows you to take full advantage of all the new features introduced in the .NET Framework 2.0. For more information, see Creating XML Readers.

The XmlParserContext class is used to construct an XmlTextReader object with context information required to parse an XML fragment or document. The XmlParserContext class can provide information such as the XmlNameTable to use, the namespace scope, and the current xml:lang and the xml:space scope.

The following lists the two constructors that utilize the XmlParserContext class.

public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext context);
public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context);

The fragType parameter specifies the XML node type, which determines whether the data will be parsed as a fragment or as a well-formed XML document. The following table lists the node type and what type of data the parser expects. Passing in any other XmlNodeType value throws an ArgumentException.

Node type

Fragment contains


Any valid element content, including a combination of elements, comments, processing instructions, CDATA, and text.

An XML declaration can also be supplied. This allows you to specify the encoding for the XML fragment.


The value of an attribute.


The contents of an entire XML document. This type enforces the XML well-formed document rules.

If the 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. Encoding can also be specified in an XML declaration, which can occur as a first node of the fragment.

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

XmlTextReader tr = new XmlTextReader("<element1> abc </element1> 
  <element2> qrt </element2>
  <?pi asldfjsd ?>
  <!-- comment -->", XmlNodeType.Element, null);
    Console.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);

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