XSD and Schema Validation

Consider the following XML document:

        <?xml version="1.0"?>
            <customer id="1" status="active">
            <customer id="1" status="archived">

We can write an XSD for this document as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" 
        <xs:element name="customers">
                    <xs:element maxOccurs="unbounded" name="customer">
                                <xs:element name="firstname" type="xs:string" />
                                <xs:element name="lastname" type="xs:string" />
                            <xs:attribute name="id" type="xs:int" use="required" />
                            <xs:attribute name="status" type="xs:string" use="required" />

Validating with an XmlReader

Here's how to plug a schema from the file customers.xsd into an XmlReader:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
    static void Main()

        XmlReaderSettings settings = new XmlReaderSettings(); 
        settings.ValidationType = ValidationType.Schema; 
        settings.Schemas.Add(null, "customers.xsd");

        XmlReader r = XmlReader.Create("customers.xml", settings);
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.