Simplified XML tutorial (7)

Source: Internet
Author: User

Directory

Development History

Comparison Between XML and HTML

Syntax details for comparison between XML and HTML

DTD for XML Verification

XML namespace

XML syntax structure

XML Schema Verification

Dom4j read/write configuration file

About SLT

XML Schema Verification

As mentioned in the previous article, using DTD, we can easily determine whether the XML to be verified complies with our defined specifications (whether the relationship between elements and attribute values are correct) however, if you want to verify the content DTD of the element, you can't do anything about it, so people have studied the new verification method-schema.

In addition to the above advantages, schema is more exciting than DTD because it itself is a good form of XML document, which makes it very easy to write a schema. Compared with a set of independent DTD, writing and maintenance are very difficult.

A schema file is an XML file. Therefore, the process of compiling a schema corresponding to an XML file is to write XML against the XML file. In this way, it is very easy to write a schema. The following shows how to compile the corresponding schema against XML

Original XML file (test2.xml)

<?xml version="1.0"encoding="ISO-8859-1"?> <shiporder orderid="889923"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="shiporder.xsd"> <orderperson>George Bush</orderperson> <shipto>  <name>John Adams</name>  <address>Oxford Street</address>  <city>London</city>  <country>UK</country> </shipto> <item>  <title>Empire Burlesque</title>  <note>Special Edition</note>  <quantity>1</quantity>  <price>10.90</price> </item> <item>  <title>Hide your heart</title>  <quantity>1</quantity>  <price>9.90</price> </item></shiporder> 

For the above XML, we start to create a schema. The principle behind this is how to describe the schema corresponding to the original XML, just as you are describing it face to face with a person.

The schema code is as follows (shiporder. XSD)

 <?xml version="1.0"encoding="ISO-8859-1" ?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="shiporder"> <xs:complexType>  <xs:sequence>   <xs:element name="orderperson"type="xs:string"/>   <xs:element name="shipto">    <xs:complexType>     <xs:sequence>      <xs:elementname="name" type="xs:string"/>      <xs:elementname="address" type="xs:string"/>      <xs:elementname="city" type="xs:string"/>      <xs:elementname="country" type="xs:string"/>     </xs:sequence>    </xs:complexType>   </xs:element>   <xs:element name="item"maxOccurs="unbounded">    <xs:complexType>     <xs:sequence>      <xs:elementname="title" type="xs:string"/>      <xs:elementname="note" type="xs:string" minOccurs="0"/>      <xs:elementname="quantity" type="xs:positiveInteger"/>      <xs:element name="price"type="xs:decimal"/>     </xs:sequence>    </xs:complexType>   </xs:element>  </xs:sequence>  <xs:attribute name="orderid"type="xs:string" use="required"/> </xs:complexType></xs:element> </xs:schema>

Code parsing:

The first line is that all XML statements do not need to be repeated.

Second, this XML (schema itself is an XML) defines a namespace.

Starting from the fourth line, there are some requirements for the original XML:

First, the root element is defined as shiporder (Row 4). Secondly, because the shiporder element has an attribute that contains other elements, it is a composite type (Row 5 ). Then, the sequence element is used to enclose its child elements (Row 10 --- row 15) in order to describe the element name and element type (row 11 ---- row 14 ), if you want to describe the constraints of the element (Row 22 ). Description of the attribute of the root element. Because it is a mandatory attribute, select the required keyword. Note that this attribute must be placed at the end (row 29)

The XML code for schema verification is similar to the DTD verification in the previous article. The Code is as follows:

package ValidateXml; import java.io.File;import java.io.IOException; import javax.xml.XMLConstants;import javax.xml.transform.stream.StreamSource;import javax.xml.validation.Schema;import javax.xml.validation.SchemaFactory;import javax.xml.validation.Validator; import org.xml.sax.ErrorHandler;import org.xml.sax.SAXException; importcom.sun.org.apache.xml.internal.utils.DefaultErrorHandler; public class XmlValidator{    private String xsdFilePath;     public XmlValidator(String xsdFilePath)    {        this.xsdFilePath =xsdFilePath;    }     public String validata(String xmlFilePath,ErrorHandler errorHandler)    {        String msg = null;        SchemaFactoryfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);        try        {           Schema schema = factory.newSchema(new File(xsdFilePath));           Validator validator = schema.newValidator();           validator.setErrorHandler(errorHandler);           validator.validate(new StreamSource(new File(xmlFilePath)));        }        catch (SAXExceptione)        {           msg = e.getMessage();           e.printStackTrace();        }        catch (IOExceptione)        {           msg = e.getMessage();           e.printStackTrace();        }        return msg;    }     public static void main(String[] args)    {        String xmlFilePath ="d://test2.xml";        String xsdFilePath ="d://shiporder.xsd";        XmlValidator my =new XmlValidator(xsdFilePath);        String msg =my.validata(xmlFilePath, new DefaultErrorHandler());       System.out.println(msg == null);    }} 

If the original XML file conforms to the description in the schema file, true is returned; otherwise, an exception is thrown to describe where it does not match, and false is returned. (The specific operations can be customized in the actual project. Here is a simple description)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.