Search code examples
xmlantxsd-validationdtdxerces

Xerces enforces Element declarations if DTD DOCTYPE is present


I have the follwoing XML document:

<!DOCTYPE root [<!ENTITY foo "bar">]>
<root>
    <child>&foo;</child>
</root>

and I want to validate it against the following XSD schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

For this I'm using a small ANT script:

<project basedir="." name="schema-validation-test" default="test">
  <target name="test">
      <schemavalidate failonerror="true" file="src.xml" nonamespacefile="schema.xsd">
          
      </schemavalidate>
  </target>
</project>

Though the XML structure is valid against the XSD I get the errors:

[schemavalidate] ...\src.xml:2:7: Elementtyp "root" muss deklariert werden.
[schemavalidate] ...\src.xml:3:12: Elementtyp "child" muss deklariert werden.

(Original messages, translated it means: 'Element type "root" must be declared')

I think I know what happens: Xerces finds the DTD declaration and tries to validate the XML against it. I need to turn off the DTD validation (without turning off the full validation) or to specify that elements or attributes that do not have a declaration do not produce an error. I played around a lot with the Xerces features (https://xerces.apache.org/xerces-j/features.html), but didn't find a satisfying setup.

Thanks for any help or hint!

Version information:

  • Java: 1.8.0_211
  • Ant: 1.9.13
  • Xerces: not sure, how to find out?

UPDATE: found my Xerces version: Xerces-J 2.7.1 (for ant, execute: <java classname="com.sun.org.apache.xerces.internal.impl.Version"/>)

Note: I'm using Ant here, but if you have a solution in Java, it may also be helpful.


Solution

  • I think you need to set the "schemaLanguage" property. Something like this:

    <project basedir="." name="schema-validation-test" default="test">
        <target name="test">
            <schemavalidate file="src.xml" noNamespaceFile="schema.xsd" failonerror="true">
                <property name="http://java.sun.com/xml/jaxp/properties/schemaLanguage" value="http://www.w3.org/2001/XMLSchema"/>
            </schemavalidate>
        </target>
    </project>
    

    Best Regards, Octavian