ASP.Net/XML/Schema

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create XML Schema

<%@ Page Language="C#"%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>
<script runat="server">    
    private StringBuilder stringBuilder = new StringBuilder();
    void Page_Load(object sender, EventArgs e)
    {        
        string ns = "http://www.w3.org/2001/XMLSchema";
        string xsdPath = MapPath("NewAuthors.xsd");        
        XmlSchema schema = new XmlSchema();                     
        
        XmlSchemaElement authorID = new XmlSchemaElement();
        authorID.Name = "authorID";
        authorID.SchemaTypeName = new XmlQualifiedName("string", ns );
        
        XmlSchemaElement authorLastName = new XmlSchemaElement();
        authorLastName.Name = "lastName";
        authorLastName.SchemaTypeName = new XmlQualifiedName("string", ns);
        
        XmlSchemaElement authorFirstName = new XmlSchemaElement();
        authorFirstName.Name = "firstName";
        authorFirstName.SchemaTypeName = new XmlQualifiedName("string", ns);
        
        XmlSchemaElement zip = new XmlSchemaElement();
        zip.Name = "zip";
        zip.SchemaTypeName = new XmlQualifiedName("unsignedInt", ns);
        
        XmlSchemaElement contract = new XmlSchemaElement();
        contract.Name = "contract";
        contract.SchemaTypeName = new XmlQualifiedName("boolean", ns);       
              
        XmlSchemaElement authorElement = new XmlSchemaElement();
        authorElement.Name = "author";        
                
        // Create an anonymous complex type for the author element
        XmlSchemaComplexType authorType = new XmlSchemaComplexType();
        XmlSchemaSequence authorSeq = new XmlSchemaSequence();
        //Add all the child elements to the sequence
        authorSeq.Items.Add(authorID);
        authorSeq.Items.Add(authorLastName);
        authorSeq.Items.Add(authorFirstName);
        authorSeq.Items.Add(zip);
        authorSeq.Items.Add(contract);
        authorType.Particle = authorSeq;     
           
        //Set the SchemaType of authors element to the complex type
        authorElement.SchemaType = authorType;               
        //Add the root authors element to the schema
        schema.Items.Add(authorElement);
        //Compile the file to check for validation errors
        schema.rupile(new ValidationEventHandler(ValidationEventHandler));                    
        FileStream stream = new FileStream(xsdPath, FileMode.Create);
        //Write the file
        schema.Write(stream);
        stream.Close();
        if (stringBuilder.ToString() == String.Empty)
            Response.Write("File written successfully");
        else
            Response.Write("Schema Creation Failed. <br>" + stringBuilder.ToString());        
    }   
    void ValidationEventHandler(object sender, ValidationEventArgs args)
    {        
        stringBuilder.Append("Validation error: " + args.Message + "<br>");                
    }    
  
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Writing XSD Schema</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>                
    </div>
    </form>
</body>
</html>



Read XML Schema and compile

<%@ Page Language="C#"%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>
<script runat="server">    
    private StringBuilder stringBuilder = new StringBuilder();
    void Page_Load(object sender, EventArgs e)
    {        
        string xsdPath = MapPath("Authors.xsd");        
        XmlSchema schema = null;
        FileStream stream = new FileStream(xsdPath, FileMode.Open);
        schema = XmlSchema.Read(stream, new ValidationEventHandler(ValidationEventHandler));
        stream.Close();        
        schema.rupile(new ValidationEventHandler(ValidationEventHandler));        
        if (schema.IsCompiled)
            DisplaySchemaObjects(schema);        
        else
            Response.Write("Schema Reading Failed. <br>" + stringBuilder.ToString());
    }
    
    void DisplaySchemaObjects(XmlSchema schema)
    {
        foreach (XmlSchemaElement elem in schema.Elements.Values)
        {            
            if (elem.ElementSchemaType is XmlSchemaComplexType)
            {                
                Response.Write("Complex Element: " + elem.Name + "<br>");
                XmlSchemaComplexType ct = (XmlSchemaComplexType)elem.ElementSchemaType;                                
                //Process the XmlSchemaComplexType                
            }
        }             
    }
    void ValidationEventHandler(object sender, ValidationEventArgs args)
    {        
        stringBuilder.Append("Validation error: " + args.Message + "<br>");                
    }    
  
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Reading XSD Schema</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>                
    </div>
    </form>
</body>
</html>

<%-- Authors.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="authors">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="author">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="authorID" type="xs:string" />
              <xs:element name="lastName" type="xs:string" />
              <xs:element name="firstName" type="xs:string" />
              <xs:element name="phone" type="xs:string" />
              <xs:element name="address" type="xs:string" />
              <xs:element name="city" type="xs:string" />
              <xs:element name="state" type="xs:string" />
              <xs:element name="zip" type="xs:unsignedInt" />
              <xs:element name="contract" type="xs:boolean" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
--%>



Validate XML with inline Schema

<%@ Page Language="C#"%>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>
<script runat="server">    
    private StringBuilder stringBuilder = new StringBuilder();
    void Page_Load(object sender, EventArgs e)
    {
        string xmlPath = MapPath("AuthorsWithInlineSchema.xml");            
        XmlReader reader = null;        
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;                
        settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler);
        //settings.ValidationFlags &= ~XmlSchemaValidationFlags.IgnoreInlineSchema;
        //settings.ValidationFlags &= ~XmlSchemaValidationFlags.IgnoreValidationWarnings;        
        settings.ValidationFlags &= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags &= XmlSchemaValidationFlags.ReportValidationWarnings;        
        reader = XmlReader.Create(xmlPath, settings);
        while (reader.Read()) 
        {            
        }
        if (stringBuilder.ToString() == String.Empty)
            Response.Write("Validation completed successfully.");
        else
            Response.Write("Validation Failed. <br>" + stringBuilder.ToString());
    }
    void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Error)
        {
            stringBuilder.Append("Validation error: " + args.Message + "<br>");                
        }       
    }    
  
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Inline XSD Schema Validation</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>                
    </div>
    </form>
</body>
</html>

<%--
<?xml version="1.0"?>
<root xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:x="urn:authors">
  <!-- Start of Schema -->
  <xs:schema targetNamespace="urn:authors">
    <xs:element name="authors">
      <xs:complexType>
        <xs:sequence>
          <xs:element maxOccurs="unbounded" name="author">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="authorID" type="xs:string" />
                <xs:element name="lastName" type="xs:string" />
                <xs:element name="firstName" type="xs:string" />
                <xs:element name="phone" type="xs:string" />
                <xs:element name="address" type="xs:string" />
                <xs:element name="city" type="xs:string" />
                <xs:element name="state" type="xs:string" />
                <xs:element name="zip" type="xs:unsignedInt" />
                <xs:element name="contract" type="xs:boolean" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <!-- End of Schema -->
  <x:authors>
      <author>
        <authorID>000-00-0001</authorID>
        <lastName>Nancy</lastName>
        <firstName>Lee</firstName>
        <phone>999 999-9999</phone>
        <address>9999 York St.</address>
        <city>Regina</city>
        <state>LA</state>
        <zip>99999</zip>
        <contract>true</contract>
      </author>
      <author>
        <authorID>000-00-0002</authorID>
        <lastName>First</lastName>
        <firstName>Last</firstName>
        <phone>415 986-7020</phone>
        <address>No Name St.</address>
        <city>Vancouver</city>
        <state>BC</state>
        <zip>88888</zip>
        <contract>true</contract>
      </author> 
  </x:authors>
</root>

--%>