How to create XML document with multiple schemas in Java?

935 views Asked by At

I have XSD which describes custom schema and which imports XLink (another schema).

Import is made with the following declaration ix main XSD:

<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd"/>

xlink.xsd file is actually located near the main XSD.

Then I configure builders with the following code

static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
static final String MY_SCHEMA_FILENAME = "mydir/myfile.xsd";
static final String MY_DATA_FILENAME = "mydir/myfile.xml";

factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        try {
            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA_FILENAME));
        }
        catch (IllegalArgumentException e) {
            throw new AssertionError(e);
        }

        try {
            builder = factory.newDocumentBuilder();
        }
        catch(ParserConfigurationException e) {
            throw new AssertionError(e);
        }

when I prepare document in memory, I set attribute the following way

imageElement.setAttribute("xlink:href", mypathvariable);

I expect this will create tag which is described following way in XSD

                        <xs:element name="image">
                            <xs:complexType>
                                <xs:attribute ref="xlink:href" use="required"/>
                            </xs:complexType>
                        </xs:element>

While creating everything works without any errors, but while saving with code

        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();

        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(new File(MY_DATA_FILENAME));

        transformer.transform(source, result);

the following error occurs:

ERROR:  'Namespace for prefix 'xlink' has not been declared.'

Where is my mistake?

1

There are 1 answers

0
Petru Gardea On BEST ANSWER

Use setAttributeNS instead, something like this:

imageElement.setAttributeNS("http://www.w3.org/1999/xlink", "href", mypathvariable);

If you want to stick with:

imageElement.setAttribute("xlink:href", mypathvariable);

Then make sure you have this defined (typically on the root element), on some element that provides scope to where your attribute is being added:

someElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

The above also shows how to control a prefix in general.