Auto complete XML with schema validation against XSD.
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.
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
These 3 attributes will enable validation and auto-suggestions to XML documents. Editors will show errors wherever the document does not follow XSD rules.
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.
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
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>
Netbeans
Here is an example of how Netbeans does the code completion. Schema Aware Code Completion in Netbeans
Intellij
Referencing XML Schemas and DTDs
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.