Reading XML Fragments with the XmlValidatingReader

The XmlValidatingReader class can read XML fragments by parsing a given string as a fragment of XML, allowing you to bypass the root level rules for well-formed XML documents.

The XmlValidatingReader method is the validating equivalent of the XmlTextReader used to construct document fragments. The XmlNodeType parameter determines how the given string is parsed. The following table demonstrates how each type is parsed.

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.

Entity references that are found in element or attribute content are processed according to the EntityHandling flag. You can pass document type definition (DTD) information that is used to resolve entities and add default attributes by using the XmlParserContext class. Passing in any other XmlNodeType enumeration throws an ArgumentException.

The XmlParserContext constructor containing the public, literal, system literal, and internal DTD subset is required if 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.

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
[C#]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
[C#]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

Validation of XML with XmlValidatingReader | Validation of XML with Schemas | XmlSchemaCollection as a Schema Cache | XmlParserContext Class