Search code examples
javaxmlattributesduplicatestransformer-model

Java Transformer class duplicates some xml node attributes when transforming


I have created this simple function in Java:

public static String prettify(Document xml) {
   String resultValue;
   StreamResult xmlOutput;

    try {
        StringWriter stringWriter = new StringWriter();
        xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer(); 
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");

        Source source = new DOMSource(xml);

        transformer.transform(source, xmlOutput); 
        resultValue = xmlOutput.getWriter().toString();
    } catch (Exception e) {
        resultValue = "";
    }
    return resultValue;
}

It is a very simple function so I can get an indented XML. The problem is that with this specific case, it is duplicating the attributes at the document element... weird. The case is an XML Document with this XML:

<?xml version='1.0'?><Document xmlns='urn:iso:std:iso:20022:tech:xsd:pain.008.001.02' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><CstmrDrctDbtInitn><GrpHdr>A</GrpHdr></CstmrDrctDbtInitn></Document>

I get:

"<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <CstmrCdtTrfInitn>
      <GrpHdr>
        A
      </GrpHdr>
 </CstmrCdtTrfInitn>

As you can see, both attributes at the are duplicated! I have tried playing with output properties, and nothing. If I add, for example, another attribute to the , say "test='whatever'", that specific attribute is NOT duplicated. Any help will be greatly appreciated


Solution

  • Thanks @forty-two for your support. I downloaded latest version of Xalan (2.7.2) from http://ftp.cixug.es/apache/xalan/xalan-j/binaries/ and added libraries:

    serializer.jar
    xalan.jar
    xercesImpl.jar
    xml-apis.jar
    

    to my project and now, evrything works as expected.