XML Validations

In this chapter we will learn more about how to create well formed xml document. The well formed xml document is xml document which is created by rules and syntax.

Your XML document must be validated, well formed and valid. It means your XML document must follow rules and syntax for declaration, element, attributes, comments and data into XML document. There are two ways to validate it.

Well-Formed XML Document

If your XML document is created by using XML syntax and rules, then you can say your XML document is Well-Formed.

You must follow the below rules to make your XML document well formed.

XML documents have XML declaration on first line

XML documents have root element

Tags must be case sensitive

Elements have must starting and closing tags

Elements must be hierarchical properly if you use them as nested

Elements attribute must be with name and value par where values must be added with single or double quotes

Note: If your XML document has any syntax error, your application will not be able to parse it or read it. Let’s look how well-formed and with error XML document displayed in web page.

Example 1: Well-Formed XML Document

Example 2: With Error XML Document

In above example 1, you can see its well-formatted and displayed properly in web page. Where in example 2, we can see there is syntax error in XML code. Some browser also mentioned where error is occurred so you may fix that easily but some are not so you must follow the rules and syntax while creating your XML documents.

XML Code for well-formed XML document

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product id="1001" >
<name>Sony Xperia R1 Dual</name>
<color>Silver</color>
<price>$650.00</price>
<discount>$20.00</discount>
</product>
</products>

Valid XML Document

If your XML document is well-formed document which follow the rules of DTD (Document Type Definition), then your XML document is valid. In short, to make your XML document valid, it must be well-formed.

While making XML document valid, you should use two type or definitions as following.

DTD (Document Type Definition)
XMl Schemas (Another form of DTD)

XML code for valid XML document

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE products SYSTEM "products.dtd">
<products>
<product id="1001" >
<name>Sony Xperia R1 Dual</name>
<color>Silver</color>
<price>$650.00</price>
<discount>$20.00</discount>
</product>
</products>