Reading XML Fragments with the XmlValidatingReader

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

Note

The XmlValidatingReader class is obsolete in the .NET Framework version 2.0. You can create a validating XmlReader instance using the XmlReaderSettings class and the Create method. For more information, see Validating XML Data with XmlReader.

XmlParserContext Class

The XmlParserContext class is used to construct an XmlValidatingReader object with the 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, document type definition (DTD), encoding, and the current xml:lang and the xml:space scope.

When constructing the XmlValidatingReader object, you must also specify the XML node type. The XML node type 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.

Type

Fragment contains

Element

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

An XML declaration can also occur as the first node. This allows you to specify the encoding for the XML fragment.

Attribute

The value of an attribute.

Document

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

Entity references that are found in element or attribute content are processed according to the EntityHandling flag. You can pass DTD information that is used to resolve entities and add default attributes by using the XmlParserContext class.

The XmlParserContext constructor containing the PUBLIC literal, SYSTEM literal, and internal DTD subset is required if the ValidationType property is DTD or Auto and resolving entities and adding default attributes is important. For all other validation types, the XmlParserContext without DTD properties can be supplied (such as schemas). Any schemas used to validate the XML fragment must be either added to the XmlSchemaCollection or referenced directly inside the XML fragment. The XmlParserContext is used to provide more information, such as namespace resolution, DTD information, and so on that is required for parsing XML fragments.

ArgumentException occurs if the ValidationType property is set to DTD and the XmlParserContext does not contain any DTD properties.

Example

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

Imports System
Imports System.Xml
 
Public Class Sample
  
   Overloads Public Shared Sub Main(args() As [String])
      Dim vr As New XmlValidatingReader("<element1> abc </element1>  <element2> qrt </element2> <?pi asldfjsd ?> <!-- comment -->", XmlNodeType.Element, Nothing)
      While vr.Read()
         Console.WriteLine("NodeType: {0} NodeName: {1}", vr.NodeType, vr.Name)
      End While
   End Sub
   ' Main
End Class
' Sample
using System;
using System.Xml;

public class Sample 
{
  public static void Main (String[] args) 
  {
  XmlValidatingReader vr = new XmlValidatingReader("<element1> abc </element1>  <element2> qrt </element2> <?pi asldfjsd ?> <!-- comment -->", XmlNodeType.Element, null);
        while(vr.Read())
    Console.WriteLine("NodeType: {0} NodeName: {1}", vr.NodeType, vr.Name);
   }
}

The following code example reads an XML fragment using the XmlParserContext to provide the required namespace from XmlNamespaceManager.

Imports System
Imports System.IO
Imports System.Xml
 
Public Class Sample
   
   Public Shared Sub Main()
      
      Dim xmlFrag As String = "<book><bk:genre>&n;</bk:genre></book>"
      Dim nt As New NameTable()
      Dim nsmanager As New XmlNamespaceManager(nt)
      ' Add a default namespace.
      nsmanager.AddNamespace(String.Empty, "www.microsoft.com")
      nsmanager.AddNamespace("bk", "www.microsoft.com/books")
      Dim internalContent As String = "<!ENTITY n 'novel'>"
      Dim context As New XmlParserContext(nt, nsmanager, "elem", Nothing, Nothing, internalContent, String.Empty, String.Empty, XmlSpace.None)
      Dim r As New XmlValidatingReader(xmlFrag, XmlNodeType.Element, context)
      r.ValidationType = ValidationType.None
      r.EntityHandling = EntityHandling.ExpandEntities
      While r.Read()
         Console.WriteLine("{0},{1},{2}", r.NodeType, r.Name, r.Value)
      End While 
   End Sub
   ' Main
End Class
' Sample
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

      string xmlFrag = "<book><bk:genre>&n;</bk:genre></book>";
      NameTable nt = new NameTable();
      XmlNamespaceManager nsmanager = new XmlNamespaceManager(nt);
     // Add a default namespace.
     nsmanager.AddNamespace (string.Empty, "www.microsoft.com");
     nsmanager.AddNamespace ("bk", "www.microsoft.com/books");
     string internalContent = "<!ENTITY n 'novel'>";
     XmlParserContext context = new XmlParserContext(nt, nsmanager, "elem",null, null, internalContent, string.Empty,
string.Empty, XmlSpace.None);
     XmlValidatingReader r = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
     r.ValidationType = ValidationType.None;
     r.EntityHandling = EntityHandling.ExpandEntities;
     while(r.Read())
        Console.WriteLine("{0},{1},{2}",r.NodeType, r.Name, r.Value);

  }
}

Fragment parsing is not possible when the ValidationType property is set to DTD because, by definition, a DTD requires that a whole document be loaded in order to perform validation.

See Also

Concepts

Reading XML with the XmlReader

Other Resources

Using the XmlReader Class