Reputation: 671
I am trying to validate a XML document that uses multiple namespaces. I want to embed tags of the secondary namespace within a document of the primary namespace. The main/primary namespace does not "know" of the extension/secondary namespace.
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<book
xmlns ="MyMain_FPI"
xmlns:ns2="MyExtension_FPI"
>
<ns2:playmusic/>
<chapter/>
<chapter/>
</book>
The Java code for validation is the following:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new Source[] {
new StreamSource(new FileInputStream("main.xsd")),
new StreamSource(new FileInputStream("extension.xsd")),
});
factory.setSchema(schema);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("test.xml"));
As you can see, I directly add the XSD files to the DocumentBuilderFactory. Those files are:
main.xsd
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="MyMain_FPI"
targetNamespace="MyMain_FPI"
elementFormDefault="qualified">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="chapter"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="chapter">
<xs:complexType/>
</xs:element>
</xs:schema>
extension.xsd
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="MyExtension_FPI"
targetNamespace="MyExtension_FPI"
elementFormDefault="qualified">
<xs:element name="playmusic">
</xs:element>
</xs:schema>
The error I get when executing the code above is
[Error] test.xml:6:18: cvc-complex-type.2.4.a: Ungültiger Content wurde beginnend mit Element 'ns2:playmusic' gefunden. '{"MyMain_FPI":chapter}' wird erwartet.
Meaning, that is unexpected within the main namespace - which is understandable, since the element itself is unknown in that namespace. I expected that elements of the extension namespace are ignored when validating the document again the main namespace and vice versa - meaning that I can embed documents following the extension namespace within the main namespace. But that is obviously not working.
What did I miss?
Upvotes: 3
Views: 2212
Reputation: 5858
Your main.xsd
is explicit in what is allowed in the book
element. If you want to allow any additional element, you'll need to state that in the main.xsd
. After which you can add any extension XSDs you want. see https://www.w3.org/TR/xmlschema-0/#any.
new main.xsd
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="MyMain_FPI"
targetNamespace="MyMain_FPI"
elementFormDefault="qualified">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" />
<xs:element maxOccurs="unbounded" ref="chapter"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="chapter">
<xs:complexType/>
</xs:element>
</xs:schema>
Upvotes: 2