Java & amp; Xml tutorial (9) Verify XML legitimacy through XSD in Java

Source: Internet
Author: User

Java & Xml tutorial (9) Verify XML legitimacy through XSD in Java

The Java XML validation API can use XSD (XML Schema Definition) to verify the validity of the XML file content. In the following case, the javax. xml. validation. Validator class is used to identify the validity of XML content through an xsd file.
The following are the content of the xsd and xml files to be used for verification.
Employee. xsd

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><schema xmlns="http://www.w3.org/2001/XMLSchema" targetnamespace="http://www.journaldev.com/Employee" xmlns:empns="http://www.journaldev.com/Employee" elementformdefault="qualified">    <element name="empRequest" type="empns:empRequest"></element>    <element name="empResponse" type="empns:empResponse"></element>    <complextype name="empRequest">        <sequence>            <element name="id" type="int"></element>        </sequence>    </complextype>    <complextype name="empResponse">        <sequence>            <element name="id" type="int"></element>            <element name="role" type="string"></element>            <element name="fullName" type="string"></element>        </sequence>    </complextype></schema></code>

Note that the XSD above contains two root elements and a namespace. The content of the following two xml files is legal:
EmployeeRequest. xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><empns:emprequest xmlns:empns="http://www.journaldev.com/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.journaldev.com/Employee Employee.xsd ">  <empns:id>5</empns:id></empns:emprequest></code>

EmployeeResponse. xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><empns:empresponse xmlns:empns="http://www.journaldev.com/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.journaldev.com/Employee Employee.xsd ">  <empns:id>1</empns:id>  <empns:role>Developer</empns:role>  <empns:fullname>Pankaj Kumar</empns:fullname></empns:empresponse></code>

The content of the following xml file does not meet the XSD constraints:
Employee. xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%3F%2D%2D%3E--><employee>    <name>Pankaj</name>    <age>29</age>    <role>Java Developer</role>    <gender>Male</gender></employee></code>

Next, let's see how to verify whether the content of the three xml files meets the XSD constraints through the program. The validateXMLSchema method accepts two parameters, the path of the xsd and xml files, respectively, if the content of the xml file is valid, this method returns true; otherwise, false.
XMLValidation. java

package com.journaldev.xml;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.SAXException;public class XMLValidation {    public static void main(String[] args) {      System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));      System.out.println("EmployeeResponse.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));      System.out.println("employee.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "employee.xml"));      }    public static boolean validateXMLSchema(String xsdPath, String xmlPath){        try {            SchemaFactory factory =                     SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);            Schema schema = factory.newSchema(new File(xsdPath));            Validator validator = schema.newValidator();            validator.validate(new StreamSource(new File(xmlPath)));        } catch (IOException | SAXException e) {            System.out.println("Exception: "+e.getMessage());            return false;        }        return true;    }}

Run the above program and the console outputs:

EmployeeRequest.xml validates against Employee.xsd? trueEmployeeResponse.xml validates against Employee.xsd? trueException: cvc-elt.1: Cannot find the declaration of element 'Employee'.employee.xml validates against Employee.xsd? false

Related Article

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.