Saxon XSLT-Transformation: How to change serialization of an empty tag from <x/> to <x></x>?

Posted by Ben on Stack Overflow See other posts from Stack Overflow or by Ben
Published on 2010-03-14T20:44:17Z Indexed on 2010/03/14 20:45 UTC
Read the original article Hit count: 351

Filed under:
|
|
|
|

Hello folks!

I do some XSLT-Transformation using Saxon HE 9.2 with the output later being unmarshalled by Castor 1.3.1. The whole thing runs with Java at the JDK 6.

My XSLT-Transformation looks like this:

<xsl:transform
version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ns="http://my/own/custom/namespace/for/the/target/document">
<xsl:output method="xml" encoding="UTF-8" indent="no" />
<xsl:template match="/">
  <ns:item>
    <ns:property name="id">
      <xsl:value-of select="/some/complicated/xpath" />
    </ns:property>
    <!-- ... more ... -->
</xsl:template>

So the thing is: if the XPath-expression /some/complicated/xpath evaluates to an empty sequence, the Saxon serializer writes <ns:property/> instead of <ns:property></ns:property>. This, however, confuses the Castor unmarshaller, which is next in the pipeline and which unmarshals the output of the transformation to instances of XSD-generated Java-code.

So my question is: How can I tell the Saxon-serializer to output empty tags not as standalone tags?

Here is what I am proximately currently doing to execute the transformation:

import net.sf.saxon.s9api.*;
import javax.xml.transform.*;
import javax.xml.transform.sax.SAXSource;
// ...

// read data
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
// ... there is some more setting up the xmlReader here ...
InputStream xsltStream = new FileInputStream(xsltFile);
InputStream inputStream = new FileInputStream(inputFile);
Source xsltSource = new SAXSource(xmlReader, new InputSource(xsltStream));
Source inputSource = new SAXSource(xmlReader, new InputSource(inputStream));
XdmNode input = processor.newDocumentBuilder().build(inputSource);

// initialize transformation configuration
Processor processor = new Processor(false);
XsltCompiler compiler = processor.newXsltCompiler();
compiler.setErrorListener(this);
XsltExecutable executable = compiler.compile(xsltSource);
Serializer serializer = new Serializer();
serializer.setOutputProperty(Serializer.Property.METHOD, "xml");
serializer.setOutputProperty(Serializer.Property.INDENT, "no");
serializer.setOutputStream(output);

// execute transformation
XsltTransformer transformer = executable.load();
transformer.setInitialContextNode(input);
transformer.setErrorListener(this);
transformer.setDestination(serializer);
transformer.setSchemaValidationMode(ValidationMode.STRIP);
transformer.transform();

I'd appreciate any hint pointing in the direction of a solution. :-) In case of any unclarity I'd be happy to give more details.

Nightly greetings from Germany, Benjamin

© Stack Overflow or respective owner

Related posts about saxon

Related posts about castor