Thursday, August 18, 2011

Validate XSD with XML

If you want to validate the XSD (XML schema) with XML document then here is the easy steps.



First you need to install libxml-ruby via gem install command.



We have 2 files. one is example.xsd and example.xml. Lets we define normal method say validate_xml_schema.

require 'libxml'
def validate_xml_schema
   begin
      schema = XML::Schema.document(XML::Document.file("#{RAILS_ROOT}/example.xsd"))
      xml_instance = XML::Document.file("#{RAILS_ROOT}/example.xml")                  
      if xml_instance.validate_schema(schema)
         puts "Successfully validate schema"
      else
         puts "Oops!! There is some problem in XML formatting"
      end     
   rescue => e
     puts "Exception:" + e.inspect
   end 
end

Here is the two example documents.

example.xml

<?xml version="1.0" encoding="UTF-8"?>
<students>
   <student>
      <roll_no>1001</roll_no>
      <name>Priyanka Pathak</name>
      <mark subject='biology'>48</mark>
      <mark subject='physics'>42</mark>
   </student>
   <student>
      <roll_no>1002</roll_no>
      <name>Rahul Pathak</name>
      <mark subject='biology'>45</mark>     
      <mark subject='physics'>43</mark>
   </student>
</students>


example.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="students">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="student"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="student">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="roll_no"/>
        <xs:element ref="name"/>
        <xs:element minOccurs="1" maxOccurs="2" ref="mark"/>    
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:element name="roll_no" type="xs:integer"/>

  <xs:element name="name" type="xs:string"/>

  <xs:element name="mark">
    <xs:complexType>
      <xs:simpleContent>
          <xs:extension base="xs:integer">
            <xs:attribute name="subject" use="required">
              <xs:simpleType>
                <xs:restriction base="xs:string">          
                  <xs:enumeration value="biology"/>
                  <xs:enumeration value="physics"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>


XSD schema defines structure of nodes and value type.
eg. roll_no must be positive integer.
      name must be string.
      mark must contain subject as attribute with option like 'biology' or 'physics' and value type as decimal.

Hope this post helps you.

No comments:

Post a Comment