Saturday, June 13, 2015

XML Validation And WellFormedNess Checking In Java

Previously we learn how to read and write a XML with different parser. Now we will concentrate how to check the wellformedness and validity of a XML file.

Now question is what is wellformedness and what is the validation of a XML file.

  1. WellFormedNess  : It is related with XML syntax of an XML document for an example : XML document must have a single root element, the elements must be properly nested, tag names cannot begin with a number or contain certain characters, and so on.
  2. Valid : A valid XML document means that the document complies with the rules of a particular document specification.This can be done with DTD(Document Type Definition) or Schema. Before a document can be valid to a standard, it must start by being well-formed. An XML document cannot be valid until it is well-formed

WellFormedNess checked in java when parse() method called. So we don't need to do any extra thing for that.

Now we go to find the way how to validate the xml file.

There are two way because some time schema definition is defined into the XML file then we need to use internal XML Validation and some time we need to validate the XML file with external schema file when schema definition is not defined into the XML file.

Here we will try to learn how to validate a XML file against an external XML Schema file.

Step 1: 
    
     Set Schema Language
        String schemaLanguage=XMLConstants.W3C_XML_SCHEMA_NS_URI;
        

Step 2:

     Create SchemaFactory Object
        SchemaFactory schemaFactory=SchemaFactory.newInstance(schemaLanguage);
        

Step 3:

      Create Schema Object
          Schema schema=schemaFactory.newSchema(new File("XSD FilePath"));
       
      If we have multiple schema file then use Source Object array

         Schema schema=schemaFactory.newSchema(new StreamSource[]{new StreamSource(new File("XSD FilePath"))});


Step 4:


     Create Validator object
        Validator xmlValidator= schema.newValidator();

Step 5:


     Now call validate method and pass XML file as a parameter to validate. 
        xmlValidator.validate(new StreamSource(new File("XML FilePath")));

Complete Code Example :


import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
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 SchemaValidationExample {

    public static void main(String[] args) {
        try {
            /**
             * Define Schema Language.
             */

            String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
           
            /**
             * Create SchemaFactory Object.
             */

            SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
           
            /**
             * Create Schema Object,here we pass Schema File
             * If we require multiple Schema File then use
             * StreamSource object array.
             */

            Schema schema = schemaFactory.newSchema(new File("file.xsd"));
           
            //To valide XML against multiple xchema file.
            //Schema schema=schemaFactory.newSchema(new StreamSource[]{new StreamSource(new File("file.xsd"))});
           
            /**
             * Create Validator Object.
             */
            Validator xmlValidator = schema.newValidator();

           
            /**
             * Validate XML File.
             */

            xmlValidator.validate(new StreamSource(new File("file.xml")));
           
        } catch (SAXException |IOException ex) {
            Logger.getLogger(SchemaValidationExample.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 

 
XSD File :
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="students" type="studentsType"/>
  <xs:complexType name="sectionnameType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:byte" name="rollno"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element type="xs:string" name="fname"/>
      <xs:element type="xs:string" name="lname"/>
      <xs:element type="sectionnameType" name="sectionname"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="id"/>
  </xs:complexType>
  <xs:complexType name="studentsType">
    <xs:sequence>
      <xs:element type="studentType" name="student"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
        

XML File :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students xsi:noNamespaceSchemaLocation="file.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <student id="1">
    <fname>TestFirstName</fname>
    <lname>TestLastName</lname>
    <sectionname rollno="1">A</sectionname>
  </student>
</students>

 
     

3 comments:

  1. How to use internal XML schema validation using webdriver?

    ReplyDelete
  2. Schema validation is a concept by which we can validate a xml with a given schema.So it may be necessary to validate any xml file with schema when we use selenium webdriver. Can you please tell us in details?

    ReplyDelete