Chủ Nhật, 10 tháng 8, 2014

Using Validator to validate in XML

Tạo một project mới với tên Module 10.1 sau đó tạo ra một file xml với tên là tomcat-users.xml như dưới đây:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="admin" password="" roles="admin,manager"/>
</tomcat-users>

Sau đó tạo ra một file xsl với tên tomcat-users-validation.xsl như dưới đây.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="tomcat-users">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="role">
          <xs:complexType>
            <xs:attribute name="rolename" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
        <xs:element maxOccurs="unbounded" name="user">
          <xs:complexType>
            <xs:attribute name="username" type="xs:string" use="required" />
            <xs:attribute name="password" type="xs:string" use="required" />
            <xs:attribute name="roles" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Sau đó là hàm main:

public static void main(String[] args) {
        try {
            DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = parser.parse(new File("tomcat-users.xml"));
            
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaFile = new StreamSource(new File("tomcat-users-validation.xsd"));
            Schema schema = factory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            
            validator.validate(new DOMSource(doc));
            System.out.println("Document file is valid!");
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(Module101_DomValidattion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


Module 10.2

Ta tạo một application với tên là Module 10.2 và copy file xml ở ví dụ trước như dưới đây:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="admin" password="" roles="admin,manager"/>
</tomcat-users>

Tiếp đó tạo ra một file xsl như dưới với tên tomcat-users-validation-2.xsl :

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="tomcat-users">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="role">
          <xs:complexType>
            <xs:attribute name="rolename" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
        <xs:element maxOccurs="unbounded" name="user">
          <xs:complexType>
            <xs:attribute name="username" type="xs:string" use="required" />
            <xs:attribute name="password" type="xs:string" use="required" />
            <xs:attribute name="roles" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>


Tiếp đó là code ở hàm main:

public static void main(String[] args) {
        try {
            InputSource is = new InputSource(new BufferedReader(new FileReader("tomcat-users.xml")));
            
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaFile = new StreamSource(new File("tomcat-users-validation-2.xsd"));
            Schema schema = factory.newSchema(schemaFile); 
            Validator validator = schema.newValidator();
            
            validator.validate(new SAXSource(is));
            System.out.println("Validated by SAX, document is valid!");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Module102_SAXValidation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException | IOException ex) {
            Logger.getLogger(Module102_SAXValidation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }



Nhận xét. 

Không cần khai viết nhiều mã lệnh khi thực thi, chỉ cần một file xsl để thực hiện validate cho dữ liệu của file xml.

Không có nhận xét nào:

Đăng nhận xét