Reading:
XSD - Autocomplete and Validate XML in IDE

XSD - Autocomplete and Validate XML in IDE

Metamug
XSD - Autocomplete and Validate XML in IDE

XML Validation

As we all know XSD (XML Schema definition) is used for validating XML. Configuration files written with XML are validated against the rules specified in XSD. But in the article, we are going to understand how we can use the XSD to write XML with autocomplete.

IDE's like Netbeans, Eclipse and some Editors provide suggestions in the XML file based on XSD provided.

Eclipse shows errors in the editor gutter by default.

Configure XML for validation and Autocomplete

To include this autocomplete and validation, we need to include the URL for the hosted XSD file in root tag of the XML.

We need to add the following 3 attributes in the root tag

  1. xmlns - To specify the namespace for the xml document
  2. xmlns:xsi - To specify the XML Schema Instance
  3. xsi:schemaLocation - The schema location for the XSI

These 3 attributes will enable validation and auto-suggestions to XML documents. Editors will show errors wherever the document does not follow XSD rules.

Adding XML Namespace Attribute

xmlsns attribute will define the namespace for the document. This need not be a valid URL. But it needs to be unique in the sense that 2 namespaces defined should be distinct.

Adding XML Schema Instance Namespace Attribute

xmlns:xsi attribute is used to specify the schema instance namespace. The standard value for this attribute is http://www.w3.org/2001/XMLSchema-instance

This namespace will be used to define the schema location further

Adding XML Schema Location

The most important part is that the URL should be hosted and working and both the URL should be correct. Also, both the URL should have space in between otherwise the validation and autocomplete would not work.

xsi:schemaLocation="http://xml.metamug.net/resource/1.0 http://xml.metamug.net/schema/resource.xsd"

Finally, if you add below all the attributes to the root element, the autocomplete works. Else it will not.

<Resource xmlns="http://xml.metamug.net/resource/1.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xml.metamug.net/resource/1.0 http://xml.metamug.net/schema/resource.xsd">
</Resource>

IDE Support

Netbeans

Here is an example of how Netbeans does the code completion. Schema Aware Code Completion in Netbeans

Intellij

Referencing XML Schemas and DTDs

Hosting the Schema Location

The XSD needs to be hosted on public url to be downloaded by the editor that supports autocompletion.

The XSD for the above XML example is hosted here. http://xml.metamug.net/schema/resource.xsd

In case, the hosted XSD is invalid xml, the autocompletion will not work.



Icon For Arrow-up
Comments

Post a comment