zoukankan      html  css  js  c++  java
  • Validate XML using a XSD (XML Schema)

    Consider this XML file howto.xml :

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <howto xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <topic>
          <title>Java</title>
          <url>http://www.rgagnon.com/topics/java-xml.html</url>
      </topic>
      <topic>
          <title>PowerBuilder</title>
          <url>http://www.rgagnon.com/topics/pb-powerscript.htm</url>
      </topic>
      <topic>
            <title>Javascript</title>
            <url>http://www.rgagnon.com/topics/js-language.html</url>
      </topic>
      <topic>
            <title>VBScript</title>
            <url>http://www.rgagnon.com/topics/wsh-vbs.html</url>
      </topic>
    </howto>

    The external howto.xsd :

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
      <xs:element name="howto">
         <xs:complexType>
          <xs:sequence>
            <xs:element name="topic" maxOccurs="unbounded">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="title" type="xs:string"/>
                  <xs:element name="url" type="httpURI"/>
                </xs:sequence>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      
      <xs:simpleType name="httpURI">
          <xs:restriction base="xs:anyURI">
            <xs:pattern value="http://.*" />
          </xs:restriction>
      </xs:simpleType>
     
    </xs:schema>

    The code (using SAX parser) to validate an XML file using a given external XSD.

    import java.io.IOException;
    
    // SAX
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    
    //SAX and external XSD
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.SchemaFactory;
    
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.InputSource;
    
    public class XMLUtils {
    
      private XMLUtils() {}
      
      // validate SAX and external XSD 
      public static boolean validateWithExtXSDUsingSAX(String xml, String xsd) 
      throws ParserConfigurationException, IOException 
      {
        try {
          SAXParserFactory factory = SAXParserFactory.newInstance();
          factory.setValidating(false); 
          factory.setNamespaceAware(true);
    
          SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
          SAXParser parser = null;
          try {
             factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource( xsd )}));
             parser = factory.newSAXParser();
          }
          catch (SAXException se) {
            System.out.println("SCHEMA : " + se.getMessage());  // problem in the XSD itself
            return false;
          }
          
          XMLReader reader = parser.getXMLReader();
          reader.setErrorHandler(
              new ErrorHandler() {
                public void warning(SAXParseException e) throws SAXException {
                  System.out.println("WARNING: " + e.getMessage()); // do nothing
                }
    
                public void error(SAXParseException e) throws SAXException {
                  System.out.println("ERROR : " + e.getMessage());
                  throw e;
                }
    
                public void fatalError(SAXParseException e) throws SAXException {
                  System.out.println("FATAL : " + e.getMessage());
                  throw e;
                }
              }
              );
          reader.parse(new InputSource(xml));
          return true;
        }    
        catch (ParserConfigurationException pce) {
          throw pce;
        } 
        catch (IOException io) {
          throw io;
        }
        catch (SAXException se){
          return false;
      }
    }
    
    public static void main (String args[]) throws Exception{ 
        System.out.println
            (XMLUtils.validateWithExtXSDUsingSAX
                ("howto.xml", "howto.xsd"));
        /*
          output :
                   true
        */           
      }
    }

    The XML can contain a reference to the XSD to be used.

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <howto xsi:noNamespaceSchemaLocation="howto.xsd"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <topic>
          <title>Java</title>
          <url>http://www.rgagnon.com/topics/java-xml.html</url>
      </topic>
    ...
    </howto>

    The code (using DOM parser) to validate an XML file using the referenced XSD :

  • 相关阅读:
    电商-订单设计(2)
    学生-课程-成绩-教师表的设计
    电商-订单设计(1)
    WCF-错误集合002
    调用 WebService 请求因 HTTP 状态 407 失败
    SQLSERVER 中的事务嵌套
    sqlserver 中的异常捕获
    c# 和 sqlserver 中的事务
    ADO_NET 数据库连接字符串大全
    break循环和continue循环
  • 原文地址:https://www.cnblogs.com/ghgyj/p/4027063.html
Copyright © 2011-2022 走看看