XML的DTD验证与Schema验证示例
Posted 开发学习笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML的DTD验证与Schema验证示例相关的知识,希望对你有一定的参考价值。
DTD验证
<!ELEMENT books (book*)>
<!ELEMENT book (name,author,price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST book id CDATA #REQUIRED>
]>
<books>
<book id="1001">
<name>java开发</name>
<author>张三</author>
<price>98.5</price>
</book>
<book id="1002">
<name>python开发</name>
<author>李四</author>
<price>89.5</price>
</book>
</books>
Schema验证
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="{books.xsd}">
<book id="1001">
<name>java开发</name>
<author>张三</author>
<price>98.5</price>
</book>
<book id="1002">
<name>python开发</name>
<author>李四</author>
<price>89.5</price>
</book>
</books>
<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:double"></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>
Schema验证测试代码
package com.bxkuaie.schema;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
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.SAXException;
public class Test {
public static void main(String[] args) throws SAXException {
//(1)创建SchemaFactory工厂
SchemaFactory sch=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
//(2)建立验证文件对象
File schemaFile=new File("books.xsd");
//(3)利用SchemaFactory工厂对象,接收验证的文件对象,生成Schema对象
Schema schema=sch.newSchema(schemaFile);
//(4)产生对此schema的验证器
Validator validator=schema.newValidator();
//(5)要验证的数据(准备数据源)
Source source=new StreamSource("books.xml");
//(6)开始验证
try {
validator.validate(source);
System.out.println("成功");
} catch (IOException e) {
System.out.println("失败");
e.printStackTrace();
}
}
}
以上是关于XML的DTD验证与Schema验证示例的主要内容,如果未能解决你的问题,请参考以下文章