XmlValidatingReader Class
Provides validation against an XML schema while reading an XML document.
Namespace: System.Xml
Assembly: System.Xml.dll
Syntax
public class XmlValidatingReader : XmlReader
Remarks
The XmlValidatingReader class provides a way to perform validation against an XML Schema Definition (XSD) or Document Type Definition (DTD) as an XML document is being read. It wraps an existing XmlReader and adds validation capabilities.
When you instantiate XmlValidatingReader, you can specify an XmlReader to read from and an optional validation type (e.g., ValidationType.Schema for XSD or ValidationType.DTD for DTD). You can then set the schema to validate against using the Schema property.
The validation errors are reported through the ValidationEventHandler. You must attach an event handler to this event to receive validation warnings and errors.
Note: It is recommended to use the XmlReader.Create method with a XmlReaderSettings object to create an XmlReader that performs schema validation. This approach is more flexible and generally preferred over using XmlValidatingReader directly.
Methods
| Name | Description |
|---|---|
| Close() | Closes this stream and underlying streams. |
| GetReaderAttribute(string name) | Gets the value of the attribute with the specified name. |
| GetReaderState() | Gets the state of the reader. |
| MoveToElement() | Moves the XmlReader to the element that has the specified attribute. |
| Read() | Moves the XmlReader to the next node. |
| ReadAttributeValue() | Reads the value of the current attribute node. |
| ReadContentAsBase64(byte[] buffer, int index, int count) | Reads the content of the current node as Base64 encoded data. |
| ReadContentAsBinHex(byte[] buffer, int index, int count) | Reads the content of the current node as BinHex encoded data. |
| ReadContentAsBoolean() | Reads the content of the current node as a Boolean. |
| ReadContentAsDateTime() | Reads the content of the current node as a DateTime. |
| ReadContentAsDecimal() | Reads the content of the current node as a Decimal. |
| ReadContentAsDouble() | Reads the content of the current node as a Double. |
| ReadContentAsInt() | Reads the content of the current node as an Int32. |
| ReadContentAsLong() | Reads the content of the current node as an Int64. |
| ReadContentAsObject() | Reads the content of the current node as an Object. |
| ReadContentAsQName(string[] prefixes, string[] namespaces) | Reads the content of the current node as a qualified name. |
| ReadContentAsString() | Reads the content of the current node as a string. |
| ReadContentAsUnsignedInt() | Reads the content of the current node as a UInt32. |
| ReadContentAsUnsignedLong() | Reads the content of the current node as a UInt64. |
| ReadElementContentAsBase64(byte[] buffer, int index, int count) | Reads the content of an element as Base64 encoded data. |
| ReadElementContentAsBinHex(byte[] buffer, int index, int count) | Reads the content of an element as BinHex encoded data. |
| ReadElementContentAsBoolean() | Reads the content of an element as a Boolean. |
| ReadElementContentAsDateTime() | Reads the content of an element as a DateTime. |
| ReadElementContentAsDecimal() | Reads the content of an element as a Decimal. |
| ReadElementContentAsDouble() | Reads the content of an element as a Double. |
| ReadElementContentAsInt() | Reads the content of an element as an Int32. |
| ReadElementContentAsLong() | Reads the content of an element as an Int64. |
| ReadElementContentAsObject() | Reads the content of an element as an Object. |
| ReadElementContentAsQName(string[] prefixes, string[] namespaces) | Reads the content of an element as a qualified name. |
| ReadElementContentAsString() | Reads the content of an element as a string. |
| ReadElementContentAsUnsignedInt() | Reads the content of an element as a UInt32. |
| ReadElementContentAsUnsignedLong() | Reads the content of an element as a UInt64. |
| ReadInnerXml() | Reads the inner XML of the current node and returns it as a string. |
| ReadOuterXml() | Reads the outer XML of the current node and returns it as a string. |
| ReadElementString() | Reads the text content of the current node and returns it as a string. |
| ReadSubtree() | Reads the rest of the current node, including all its descendants, and returns it as a new XmlReader. |
| ResolveEntity() | Resolves the entity in the DTD. |
Properties
| Name | Description |
|---|---|
| AttributeCount | Gets the number of attributes on the current node. |
| BaseURI | Gets the base URI of the current node. |
| CanResolveEntity | Gets a value indicating whether the reader can resolve entities. |
| CharsetSettings | Gets the character set information for the current document. |
| CheckOutDate | Gets the date of checkout. |
| CheckOutNumber | Gets the checkout number. |
| CheckOutStatus | Gets the checkout status. |
| CheckOutUser | Gets the checkout user. |
| ClaimDate | Gets the date of claim. |
| ClaimNumber | Gets the claim number. |
| ClaimStatus | Gets the claim status. |
| ClaimUser | Gets the claim user. |
| CommentValue | Gets the value of the comment. |
| Data | Gets the data. |
| Depth | Gets the depth of the current node in the XML document. |
| DisableUiDevices | Gets or sets a value that indicates whether UI devices are disabled. |
| Document | Gets the XmlDocument. |
| DocType | Gets the XmlDocumentType. |
| Encoding | Gets the encoding of the current XML declaration. |
| EOF | Gets a value indicating whether the reader is at the end of the stream. |
| HasAttributes | Gets a value indicating whether the current node has attributes. |
| HasValue | Gets a value indicating whether the node has a value. |
| IsDefault | Gets a value indicating whether the attribute is defaulted. |
| IsLocalName | Gets a value indicating whether the local name is the same as the attribute name. |
| IsXmlns | Gets a value indicating whether the attribute is an XML namespace attribute. |
| Item(int i) | Gets the value of the attribute with the specified index. |
| Item(string name) | Gets the value of the attribute with the specified name. |
| Item(string localName, string namespaceURI) | Gets the value of the attribute with the specified local name and namespace URI. |
| Lang | Gets the xml:lang attribute value of the current node. |
| LocalName | Gets the local name of the current node. |
| LogicalDirectory | Gets the logical directory. |
| MasterData | Gets the master data. |
| Name | Gets the qualified name of the current node. |
| NamespaceURI | Gets the namespace URI of the current node. |
| NamespaceManager | Gets the XmlNamespaceManager. |
| NamespaceManagerId | Gets the ID of the namespace manager. |
| NamespaceManagerMode | Gets the mode of the namespace manager. |
| NodeCount | Gets the total number of nodes read so far. |
| NodeLatency | Gets the latency of the node. |
| NodeType | Gets the type of the current node. |
| NormalizationForm | Gets a value indicating the normalization form to use. |
| Prefix | Gets the namespace prefix of the current node. |
| ProcessData | Gets the process data. |
| ProcessDefinition | Gets the process definition. |
| ProcessDefinitionId | Gets the process definition ID. |
| ProcessDefinitionName | Gets the process definition name. |
| ProcessId | Gets the process ID. |
| ProcessName | Gets the process name. |
| ProcessType | Gets the process type. |
| ProcessingInstructions | Gets the processing instructions. |
| ProcessVersion | Gets the process version. |
| Quotas | Gets the quotas. |
| Reader | Gets the underlying XmlReader. |
| ReadState | Gets the state of the reader. |
| Root | Gets the root element. |
| Schema | Gets or sets the schema collection to use for validation. |
| SchemaCollection | Gets the collection of schemas. |
| SkipWhitespace | Gets or sets a value indicating whether to skip whitespace. |
| State | Gets the state of the reader. |
| Stream | Gets the stream. |
| SuppressWhitespace | Gets or sets a value indicating whether to suppress whitespace. |
| ValidationEventHandler | Gets or sets the delegate that handles validation events. |
| ValidationType | Gets or sets the type of validation to perform. |
| Value | Gets the value of the current node. |
| Values | Gets the values. |
| XmlBaseURI | Gets the base URI of the current node. |
| XmlCharCount | Gets the character count. |
| XmlEncoding | Gets the XML encoding. |
| XmlFileCount | Gets the file count. |
| XmlFilePath | Gets the file path. |
| XmlFileType | Gets the file type. |
| XmlFileSize | Gets the file size. |
| XmlFileSizeInBytes | Gets the file size in bytes. |
| XmlFileTypeId | Gets the file type ID. |
| XmlFileTypeName | Gets the file type name. |
| XmlIndent | Gets or sets a value indicating whether to indent the XML. |
| XmlItemCount | Gets the item count. |
| XmlName | Gets the XML name. |
| XmlNamespace | Gets the XML namespace. |
| XmlNamespaceURI | Gets the XML namespace URI. |
| XmlNodeCount | Gets the node count. |
| XmlPrefix | Gets the XML prefix. |
| XmlString | Gets the XML string. |
| XmlVersion | Gets the XML version. |
Events
| Name | Description |
|---|---|
| ValidationEventHandler | Fired when a validation warning or error occurs. |
Examples
Validating an XML Document with an XSD Schema
using System;
using System.Xml;
using System.Xml.Schema;
public class Example
{
public static void Main(string[] args)
{
// Create an XmlReader to read the XML document
XmlReader reader = XmlReader.Create("myDocument.xml");
// Create an XmlValidatingReader
XmlValidatingReader validatingReader = new XmlValidatingReader(reader);
// Load the XSD schema
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "mySchema.xsd");
validatingReader.Schemas.Add(schemaSet);
// Set the validation type to Schema
validatingReader.ValidationType = ValidationType.Schema;
// Add a handler for validation events
validatingReader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Read the XML document and perform validation
while (validatingReader.Read())
{
// Process the XML nodes here
}
validatingReader.Close();
}
// Callback method for validation events
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
Console.WriteLine($"Warning: {args.Message}");
}
else if (args.Severity == XmlSeverityType.Error)
{
Console.WriteLine($"Error: {args.Message}");
}
}
}
myDocument.xml:
<?xml version="1.0" encoding="utf-8"?>
<bookstore xmlns="http://www.contoso.com/books">
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
mySchema.xsd:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.contoso.com/books"
xmlns:book="http://www.contoso.com/books"
elementFormDefault="qualified">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element name="book" type="book:BookType" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="BookType">
<xs:sequence>
<xs:element name="title" type="xs:string" />
<xs:element name="author" type="xs:string" />
<xs:element name="year" type="xs:integer" />
<xs:element name="price" type="xs:decimal" />
</xs:sequence>
<xs:attribute name="category" type="xs:string" use="required" />
</xs:complexType>
</xs:schema>