zoukankan      html  css  js  c++  java
  • 检查dtd和Xschema文件限制下的xml文件是否符合的Java文件

    先来xml文件:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <!DOCTYPE orders SYSTEM "orders.dtd">
     3 <orders> <!-- 所有订单信息 -->
     4     <order orderDate="2003-10-20"> <!--orderDate为日期型 -->
     5         <shipTo country="CN"><!--country必须出现 -->
     6             <name>张三峰</name> <!-- 收件人 -->
     7             <street>市中区滨河路778号5+3大酒店</street> <!-- 县/区及街道地址 -->
     8             <city>乐山市</city> <!-- 市/区 -->
     9             <state>四川省</state> <!-- 省/自治区/直辖市 -->
    10             <phone>13999999999</phone> <!-- 联系电话 -->
    11         </shipTo>
    12         <items> <!-- 商品列表,item应至少出现1次 -->
    13             <item partNum="872-AA"> <!--商品编号,必须有 -->
    14                 <productName>Lawnmower</productName><!-- 商品名称 -->
    15                 <quantity>1</quantity> <!-- 购买数量 -->
    16                 <price>148.95</price> <!-- 单价 -->
    17                 <shipDate>2003-10-21</shipDate> <!-- 配送日期 -->
    18             </item>
    19             <item partNum="926-AA">
    20                 <productName>Baby Monitor</productName>
    21                 <quantity>1</quantity>
    22                 <price>39.98</price>
    23                 <shipDate>2003-10-22</shipDate>
    24             </item>
    25         </items>
    26     </order>
    27 </orders>
    orders.xml

    再来对应的dtd文件:

     1 <!ELEMENT orders (order*)>
     2 <!ELEMENT order (shipTo*, items+)>
     3 
     4 <!ELEMENT shipTo (name, street, city, state, phone)>
     5 <!ELEMENT name (#PCDATA)>
     6 <!ELEMENT street (#PCDATA)>
     7 <!ELEMENT city (#PCDATA)>
     8 <!ELEMENT state (#PCDATA)>
     9 <!ELEMENT phone (#PCDATA)>
    10 
    11 <!ELEMENT items (item+)>
    12 <!ELEMENT item (productName, quantity, price, shipDate)>
    13 <!ELEMENT productName (#PCDATA)>
    14 <!ELEMENT quantity (#PCDATA)>
    15 <!ELEMENT price (#PCDATA)>
    16 <!ELEMENT shipDate (#PCDATA)>
    17 
    18 <!ATTLIST order orderDate CDATA #REQUIRED>
    19 <!ATTLIST shipTo country CDATA #REQUIRED>
    20 <!ATTLIST item partNum CDATA #REQUIRED>
    orders.dtd

    <!--应该有些地方限制得不太合理,但是可以运行出来,这里主要记录一下Java文件-->

    下面是对应的检查的Java类:

     1 import javax.xml.parsers.DocumentBuilder;
     2 import javax.xml.parsers.DocumentBuilderFactory;
     3 import org.w3c.dom.Document;
     4 
     5 public class XmlDtdCheck {
     6 
     7     public static void main(String[] args) {
     8         // TODO Auto-generated method stub
     9         try {
    10             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    11             factory.setValidating(true);
    12             
    13             DocumentBuilder builder = factory.newDocumentBuilder();
    14             Document doc1 = (Document) builder.parse("orders.xml");
    15             Document doc2 = (Document) builder.parse("citizen.xml");
    16             // System.out.println(doc.getNodeValue());
    17             // doc并不是null,它是一个对象
    18         } catch (Exception e) {
    19             // TODO: handle exception
    20             System.err.println("ERROR!!!" + e.getMessage());
    21         }
    22     }
    23 
    24 }
    TestDTD.java

    <!--这里只是转成了document类,并没有使用-->

    然后又是一个严格一点的Java类:

     1 import java.io.File;
     2 
     3 import java.io.*;
     4 import org.xml.parsers.*;
     5 import org.w3c.dom.*;
     6 import java.util.Scanner;
     7 
     8 public class TestValidate {
     9 
    10     public static void main(String[] args) {
    11         // TODO Auto-generated method stub
    12         try {
    13             DocumentBuilderFacory factor = DocumentBilderFactory.newInstance();
    14             factor.setValidating(true);
    15             DocumentBuilder builder = factory.newDocumentBuilder();
    16             MyHandler handler = new MyHandler();
    17             builder.setErrorHandler(handler);
    18             Document document = builder.parse(new File("orders.xml"));
    19             
    20             if(handler.errorMessage == null) {
    21                 System.out.println("文件是有效的");
    22             } else {
    23                 System.out.println("文件是无效的");
    24             }
    25         } catch (Exception e) {
    26             System.out.println(e);
    27         }
    28     }
    29 }
    30 
    31 class MyHandler extends DefaultHandler {
    32     String errorMessage = null;
    33     
    34     public void error(SAXParseException e) throws SAXException {
    35         errorMessage = e.getMessage();
    36         System.out.println("一般错误"+errorMessage);
    37     }
    38     
    39     public void fatalError(SAXParseException e) throws SAXException {
    40         errorMessage = e.getMessage();
    41         System.out.println("致命错误"+errorMessage);
    42     }
    43 }
    TestValidate.java

    代码未经验证,请检验后运行。


    接下来是验证Schema文件下的XML文件的有效性。

    老规矩——XML文件:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <orders xmlns="http://www.w3school.com.cn"
     3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4         xsi:schemaLocation="http://www.w3school.com.cn orders.xsd"> <!-- 所有订单信息 -->
     5     <order> <!-- 订单,至少包含1个订单 -->
     6         <orderDate>2018-05-20</orderDate><!--orderDate为日期型 -->
     7         <shipTo country="CN"><!-- 配送信息,country属性必须出现 -->
     8             <name>张三峰</name> <!-- 收件人,长度小于50 -->
     9             <street>市中区滨河路778号5+3大酒店</street> <!-- 县/区及街道地址 -->
    10             <city>乐山市</city> <!-- 市/区,长度小于50 -->
    11             <state>四川省</state> <!-- 省/自治区/直辖市,长度小于50 -->
    12             <phone>13999999999</phone> <!-- 联系电话,要求必须是1开头,后面第2位数字3-9,再后面是9个数字 -->
    13         </shipTo>
    14         <items> <!-- 商品列表,item应至少出现1次 -->
    15             <item partNum="872-AA"> <!-- 商品编号属性,必须有 -->
    16                 <productName>香辣鸡翅</productName><!-- 商品名称,长度小于50 -->
    17                 <quantity>1</quantity> <!-- 购买数量,至少是1 -->
    18                 <price>18.95</price> <!-- 单价为浮点数,大于0.0 -->
    19                 <shipDate>2018-05-21</shipDate> <!-- 配送日期 -->
    20             </item>
    21             <item partNum="926-AA">
    22                 <productName>烧烤五花肉</productName>
    23                 <quantity>20</quantity>
    24                 <price>39.98</price>
    25                 <shipDate>2018-05-20</shipDate>
    26             </item>
    27         </items>
    28     </order>
    29 </orders>
    30 
    31 <!-- 
    32 xmlns="http://www.example.org/01"
    33         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    34         xsi:noNameSpaceSchemaLocation="orders.xsd"
    35  -->
    orders.xml

    xsd文件:

      1 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      2             targetNamespace="http://www.w3school.com.cn"
      3             xmlns="http://www.w3school.com.cn"
      4             elementFormDefault="qualified">
      5     <xsd:element name="orders">
      6         <xsd:complexType>
      7             <xsd:sequence>
      8                 <xsd:element ref="order" minOccurs="1" maxOccurs="unbounded"></xsd:element>
      9             </xsd:sequence>
     10         </xsd:complexType>
     11     </xsd:element>
     12     
     13     <xsd:element name="order">
     14         <xsd:complexType>
     15             <xsd:sequence>
     16                 <xsd:element name="orderDate" type="xsd:date" minOccurs="1" maxOccurs="1"></xsd:element>
     17                 <xsd:element ref="shipTo" minOccurs="1" maxOccurs="1"></xsd:element>
     18                 <xsd:element ref="items" minOccurs="1" maxOccurs="1"></xsd:element>
     19             </xsd:sequence>
     20         </xsd:complexType>
     21     </xsd:element>
     22     
     23     <xsd:element name="shipTo">
     24         <xsd:complexType>
     25             <xsd:sequence>
     26                 <xsd:element ref="name"></xsd:element>
     27                 <xsd:element name="street"></xsd:element>
     28                 <xsd:element name="city"></xsd:element>
     29                 <xsd:element name="state"></xsd:element>
     30                 <xsd:element ref="phone"></xsd:element>
     31             </xsd:sequence>
     32             <xsd:attribute name="country" type="xsd:string" use="required"></xsd:attribute>
     33         </xsd:complexType>
     34     </xsd:element>
     35     
     36     <xsd:element name="items">
     37         <xsd:complexType>
     38             <xsd:sequence>
     39                 <xsd:element ref="item" minOccurs="1" maxOccurs="unbounded"></xsd:element>
     40             </xsd:sequence>
     41         </xsd:complexType>
     42     </xsd:element>
     43     
     44     <xsd:element name="item">
     45         <xsd:complexType>
     46             <xsd:sequence>
     47                 <xsd:element ref="productName"></xsd:element>
     48                 <xsd:element ref="quantity"></xsd:element>
     49                 <xsd:element ref="price"></xsd:element>
     50                 <xsd:element name="shipDate" type="xsd:date"></xsd:element>
     51             </xsd:sequence>
     52             <xsd:attribute name="partNum" type="xsd:string" use="required"></xsd:attribute>
     53         </xsd:complexType>
     54     </xsd:element>
     55     
     56     <xsd:element name="name">
     57         <xsd:simpleType>
     58             <xsd:restriction base="xsd:string">     
     59                 <xsd:minLength value="0"/>
     60                 <xsd:maxLength value="50"/>
     61             </xsd:restriction>
     62         </xsd:simpleType>
     63     </xsd:element>
     64     
     65     <xsd:element name="phone">
     66         <xsd:simpleType>
     67             <!-- <xsd:restriction base="xsd:integer">
     68                 <xsd:minInclusive value="13000000000"></xsd:minInclusive>
     69                 <xsd:maxInclusive value="19999999999"></xsd:maxInclusive>
     70             </xsd:restriction> -->
     71             <xsd:restriction base="xsd:string">
     72                 <xsd:minLength value="11"></xsd:minLength>
     73                 <xsd:maxLength value="11"></xsd:maxLength>
     74                 <xsd:pattern value="1[3-9]{1}[0-9]{9}"></xsd:pattern>
     75             </xsd:restriction>
     76         </xsd:simpleType>
     77     </xsd:element>
     78     
     79     <xsd:element name="productName">
     80         <xsd:simpleType>
     81             <xsd:restriction base="xsd:string">
     82                 <xsd:maxLength value="50"/>
     83             </xsd:restriction>
     84         </xsd:simpleType>
     85     </xsd:element>
     86     
     87     <xsd:element name="quantity">
     88         <xsd:simpleType>
     89             <xsd:restriction base="xsd:integer">
     90                 <xsd:minInclusive value="1" />
     91             </xsd:restriction>
     92         </xsd:simpleType>
     93     </xsd:element>
     94     
     95     <xsd:element name="price">
     96         <xsd:simpleType>
     97             <xsd:restriction base="xsd:float">
     98                 <xsd:minInclusive value="0.1"></xsd:minInclusive>
     99             </xsd:restriction>
    100         </xsd:simpleType>
    101     </xsd:element>
    102 </xsd:schema>
    orders.xsd

    验证xml文件有效性的Java文件:

     1 import java.io.File;
     2 
     3 import javax.xml.transform.stream.StreamSource;
     4 import javax.xml.validation.Schema;
     5 import javax.xml.validation.SchemaFactory;
     6 import javax.xml.validation.Validator;
     7 
     8 import org.xml.sax.SAXException;
     9 import org.xml.sax.SAXParseException;
    10 import org.xml.sax.helpers.DefaultHandler;
    11 
    12 public class TestXSD {
    13 
    14     public static void main(String[] args) {
    15         // TODO Auto-generated method stub
    16         File xsdfile = new File("orders.xsd");
    17         File xmlfile = new File("orders.xml");
    18         Handler errorHandler = null;
    19         try {
    20             SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    21             Schema schema = schemaFactory.newSchema(xsdfile);
    22             Validator validator = schema.newValidator();
    23             errorHandler = new Handler();
    24             validator.setErrorHandler(errorHandler);
    25             validator.validate(new StreamSource(xmlfile));
    26         } catch (Exception e) {
    27             System.out.println(e);
    28         }
    29         if (errorHandler.errorMessage == null) {
    30             System.out.println("XML 文件:" + xmlfile.getName()+"符合模式");
    31         } else {
    32             System.out.println("XML 文件:" + xmlfile.getName()+"不符合模式");
    33         }
    34     }
    35 }
    36 
    37 class Handler extends DefaultHandler {
    38     String errorMessage = null;
    39     
    40     public void error(SAXParseException e) throws SAXException {
    41         errorMessage = e.getMessage();
    42         int row = e.getLineNumber();
    43         int colums = e.getColumnNumber();
    44         System.out.println("一般错误"+errorMessage+"位置:"+row+","+colums);
    45     }
    46     
    47     public void fatalError(SAXParseException e) throws SAXException {
    48         errorMessage = e.getMessage();
    49         int row = e.getLineNumber();
    50         int colums = e.getColumnNumber();
    51         System.out.println("致命错误"+errorMessage+"位置:"+row+","+colums);
    52     }
    53 }
    TestXSD.java
  • 相关阅读:
    缓存
    java内存模型—先行发生原则
    Java中的阻塞队列
    java的Map
    事务传播性、隔离性与MVCC
    final修饰符
    领域驱动设计和实践
    对象转换利器之Dozer
    SharePoint Iframe 报错“此内容不能显示在一个框架中”
    使用SVG symbols建立图标系统
  • 原文地址:https://www.cnblogs.com/Ddlm2wxm/p/9193035.html
Copyright © 2011-2022 走看看