Schema技术的使用小结.

首先编写Schema,对要编写的XML进行规范

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
    <xs:element name="books">
        <xs:complexType>
            <xs:sequence> <!--按照序列编辑  -->
                <xs:element name="book" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name ="name" type="xs:string"></xs:element>
                            <xs:element name ='author' type="xs:string"></xs:element>
                            <xs:element name ="price" type="xs:string"></xs:element>
                        </xs:sequence>
                        <xs:attribute name ="id" type="xs:positiveInteger" use="required"></xs:attribute>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

这里是根据规范写的xml文档

<?xml version ="1.0" encoding="UTF-8"?>
<books  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
 xsi:noNamespaceSchemaLocation = "{book1.xsd}">
	<book  id="1">
		<name>洛洛历险记</name>
		<author>落落</author>
		<price>98.3</price>
	</book>
</books>

编写java代码判断是够正确

 1 import java.io.File;
 2 import java.io.IOException;
 3 import javax.xml.transform.Source;
 4 import javax.xml.transform.stream.StreamSource;
 5 import javax.xml.validation.Schema;
 6 import javax.xml.validation.SchemaFactory;
 7 import javax.xml.validation.Validator;
 8 
 9 import org.xml.sax.SAXException;
10 /**
11  * Schema技术验证编写的xml是否符合规范
12  * @author 小王同学
13  *
14  */
15 public class Test {
16     public static void main(String[] args) throws SAXException {
17         //1.创建SchemaFactory工厂
18         SchemaFactory sch =SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");//这里必须要写这个
19         //2.建立验证文件对象
20         File schemaFile = new File("book1.xsd");//xsd的文件规范
21         //3.利用schemaFactory工厂接受文件对象,生成schema对象
22         Schema sce = sch.newSchema(schemaFile);
23         //4.产生对此schema的验证器
24         Validator validator=  sce.newValidator();
25         //5.要准备数据源
26         Source source =new StreamSource("book.xml");//需要验证的xml文件
27         //6.开始验证.
28         try {
29             validator.validate(source);
30             System.out.println("成功!");
31         } catch (IOException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         }
35         
36     }
37 }

努力.

原文地址:https://www.cnblogs.com/xw1024/p/11244205.html