Tuesday, August 3, 2010

XML Validation with Eclipse

When I'm doing serious schema work, I typically use XMLSpy, but for simple schema validation it isn't worth leaving the IDE. As of late, I've been using the SpringSource IDE, which comes with XML plugins pre-installed. With the plugins, XML validation is simple enough. You just need to make sure you have the schemaLocation defined in your XML.

Let's say I have a simple document:
<zoo>
<animal>cat</animal>
</zoo>

If you open the document, you can right click and Validate the document. If there is no associated schema, you'll receive a warning that says:
No grammar constraints (DTD or XML schema) detected for the document.


To rectify that, you'll need to specify the schema location in the XML. That will require namespaces. Let's assume we have the following simple schema with namespaces:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.skookle.com/philly"
xmlns:philly="http://www.skookle.com/philly" >
<xsd:complexType name="zoo">
<xsd:sequence>
<xsd:element name="animal" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>

<xsd:element name="zoo" type="philly:zoo"/>
</xsd:schema>


Now, lets revisit the simple XML to add namespaces and a schemaLocation element that references the above xsd. (zoo.xsd)


<philly:zoo xmlns:philly="http://www.skookle.com/philly"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.skookle.com/philly zoo.xsd">
<animal>cat</animal>
</philly:zoo>



Note: To get the schemaLocation attribute you'll need the XMLSchema-instance namespace.

Now, you can right-click on the XML and it will validate. Also, you'll get the fancy element completion while you type. Rock on, even less reason to leave the IDE. =)

No comments: