Validating XML


Today, we will discuss further more about XML.

Validating XML

We can use either schemas or DTD (Document Type Definition) to validate an XML file. DTD is an obsolete way of validating XML. Schema is widely used now and has better features than in DTD and they are more powerful in may ways.
  • The strongest point of schema is, it supports data types. Therefore the inputs of the XML document can be validated against the data types.
  • Also schema can have restrictions to input data. Therefore it is secured to use schema.

Writing XSD (XML Schema Definition)

First we need to write an XML schema to validate the XML document.

We will create an XSD for the following XML document.

  Xperia Z2a
   Android v4.4.2
   Quad-core 2.3 GHz
   HTML 5

 <mobilephone IMEI="0876666339988">
  Lucid 3
   Android v4.4.2
   Quad-core 1.2 GHz

Let’s start writing XSD.

XSD elements

There are two types of element types.

  • Simple elements

Simple element is an element with no child elements and it does not have attributes. It can be defined in XSD as follows.

<xs:element name="model" type="xs:string"/>
The available data types in XSD are,

  • xs:string
  • xs:integer
  • xs:boolean
  • xs:decimal
  • xs:date
  • xs:time
Simple elements can have default values or fixed values.

<xs:element name="model" type="xs:string" fixed="D6563"/>
<xs:element name="model" type="xs:string" default="D6563"/>

  • Complex elements

XSD complex types can have child elements and attribute values.
In our XML example, tag has its child elements. So it is a complex element.

<xs:element name="dimensions">
      <xs:element name="width" type="xs:string"/>
      <xs:element name="height" type="xs:string"/>
      <xs:element name="depth" type="xs:string"/>

XSD attributes

XSD attributes syntax is similar to simple type.

<xs:attribute name="IMEI" type="integer"/>

Additionally it can have a value for required field. If the attribute is mandatory required field must contain the value ‘yes’.

<xs:attribute name="IMEI" type="integer" required="yes"/>

Restrictions for elements

Now, you can write an XML schema with simple and complex elements. Let’s see how we can add restrictions for elements.

We can use tag to restrict our element. We can have minimum value, maximum value

<xs:element name="weight">
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="50"/>
      <xs:maxInclusive value="500"/>

Also you can use the following restriction methods.

<xs:pattern value="[a-zA-Z]"/>

<xs:minLength value="5"/>
<xs:maxLength value="8"/>

Hope you got an idea about writing XML schema for a given small XML document.

See you with more in the next post….

Leave a comment

Your email address will not be published. Required fields are marked *