Validating XML Documents in Eclipse using DTD
Eclipse is able to validate any XML document on-the-fly if you provide a DTD. As you know, XML document is identified by one of two kinds of ID: public and system. The system identifier is basically the URL of the DTD defining the language used in the document. When you start editing an XML document, Eclipse tries to recognize the document type and match it to one of the types it knows (like one of supported XHTML flavors, Web Application Deployment Descriptor etc). However, if you are working with a language that is not known to Eclipse, it will be unable to validate the document. It will only be able to ensure that the document is well-formed.
Consider the following sample DTD:
<!ELEMENT test-root (test-header, test-body)> <!ATTLIST test-root version CDATA #REQUIRED > <!ELEMENT test-header (#PCDATA)> <!ATTLIST test-header id ID #IMPLIED > <!ELEMENT test-body (#PCDATA)>
If you want to be able to write a valid XML document conforming to this DTD in Eclipse, you could save this DTD in your filesystem and then specify its system ID as the pathname:
<!DOCTYPE SYSTEM "/Users/nik/samples/test.dtd"> ...
However, this is not the best approach, ideally you should use the right system ID (or not to use it at all). At the end, this ID may be used by your application that handles these XML files.
Most of the XML processors have so-called “XML Catalog” that contains the mapping between the document IDs and the actual locations of the DTDs. In Eclipse you can access the catalog by opening the “Preferences” dialog, typing the word “catalog” in the search box and selecting “XML Catalog”
In this catalog you can see all the document types (with their public IDs) known to Eclipse. And you can add your own mappings here. Click on “Add..” button and fill the pop-up dialog as follows:
- Location - the location of your DTD file (in the workspace or anywhere in the filesystem)
- Key Type - select the “Public ID”, this is the parameter Eclipse will be looking for in your document
- Key - put the value of the public ID you want to use (quot;-//MyHowTo//Test Language 1.0//EN" in our example)
Now you can use a document like this to test the validation:
<!DOCTYPE test-root PUBLIC "-//MyHowTo//Test Language 1.0//EN" "http://www.myhowto.org/dtds/test.dtd"> <test-root> <test-header/> </test-root>
Eclipse now takes the public ID of your XML document, looks for this key in the catalog where the key type is “Public ID” and uses the DTD from the location you have mapped to this key. You can map URIs to the locations or even the system IDs if you want. You can also manage (import and export) multiple catalogs in Eclipse.
blog comments powered by Disqus