JAXB2 Removing standalone="yes" on XML

Viewed 24

I need to remove the standalone="yes" on my XML.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I tried with this code:

    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);            
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\">");

The result on XML - Duplicate information:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <?xml version="1.0" encoding="UTF-8">

Does anyone know how to remove standalone="yes"?

Marshall code:

        try {

        JAXBContext context = JAXBContext.newInstance(DataToXML.class);

        Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
        marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\">");

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter writer = new StringWriter();
        marshaller.marshal(xml, writer);

        System.out.println(writer.toString());
        
        marshaller.marshal(xml, new File("test.xml"));

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
1 Answers

XSLT transformation to the rescue.

It is possible to control almost any XML aspect via <xsl:output .../> clause attributes.

One of them is standalone = 'yes' or 'no'

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" standalone="no" omit-xml-declaration="no" encoding="UTF-8" indent="yes" />
   <xsl:strip-space elements="*"/>

   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>
Related