-->

XSD Validation in Eclipse: “No grammar constraints

2019-07-23 13:34发布

问题:

I created a new project in Eclipse just to validate a xml thanks to the corresponding xsd. I wrote both the xsds and the xml files.

The main XSD is like:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://www.myurl.com/schemas" 
  targetNamespace="http://www.myurl.com/schemas" 
  version="1.0">
<xs:include schemaLocation="other_xsd.xsd"/>
[...]

The other_xsd.xsd is in the same directory and is like:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://www.myurl.com/schemas" 
  targetNamespace="http://www.myurl.com/schemas">

It mostly contains complexTypes used in the main xsd

The xml example file also is in the same directory and is like:

<?xml version="1.0" encoding="UTF-8"?>
<myTag xmlns="http://www.myurl.com/schemas" myAttributes="2011-09-07">

All those three files have been loaded within the same directory in my Eclipse project. Yet I keep having this warning:

No grammar constraints (DTD or XML schema) detected for the document. example.xml XMLValidation/Test line 1 XML Problem

What is missing in my xml or in my xsd so that I can validate my xml file?

回答1:

Under Preferences -> XML -> XML Catalog, add a user specified entry. Put the schema path/filename in the Location field (using the Workspace or File System buttons if desired). At that point the Key field should be populated with your namespace. Click OK a couple times to exit out, then right-click your xml file and click Validate. Eclipse should match your "xmlns" attribute with the "Key", and use the appropriate schema.



回答2:

You need to tell eclipse xml processor where to find the schema. Either edit Preferences->XML->XML Catalog so that your namespace is mapped to the schema resource, or just include a schemaLocation in your instance document. Assuming your main schema is main.xsd:

<myTag xmlns="http://www.myurl.com/schemas" 
       myAttributes="2011-09-07"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.myurl.com/schemas main.xsd" >