0
votes

I have written code to pretty format my XML. It is working fine but XML which has encoding ISO-8859-1 it changes to encoding="UTF-8" I don't understand why can anyone tell where I am going wrong.

This is XSL file

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

This is my code snippet for pretty format in java

 private void prettyFormat(File f) {
    logger.info("Formatting file: " + f);

    try {
      File file = new File(outputPath.toString()+"/"+f.getName());
      FileCopyUtils.copy(f, file);
      File xslFile=null;
      javax.xml.transform.Source xmlSource =new javax.xml.transform.stream.StreamSource(f);
      StreamResult sr = new StreamResult(new File(outputPath.toString()+"/"+file.getName()));
      Transformer transformer = getTransformer();
      transformer.transform(xmlSource, sr);

    } catch (Exception e) {
      logger.error("Failed to format file " + f.getName(), e);
    }

  }

  private Transformer getTransformer() throws TransformerConfigurationException {
    File xslFile=null;
    javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
    javax.xml.transform.Transformer trans = transFact.newTransformer();
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    if (System.getProperty(BASEDIR) == null || isRunningInTests()) {
      xslFile = new File("assembly" + File.separator + "etc" + File.separator + "strip-space.xsl");
    }      else{
      xslFile = new File(getBaseDir() + File.separator + "etc" + File.separator + "strip-space.xsl");
    }

    logger.info("The path of file:::: " + xslFile);
    trans = transFact.newTransformer(
      new StreamSource(xslFile));
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty("indent", "yes");

    return trans;
  }

Please tell me whether I have set the wrong property or something else.

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?> changes to this header <?xml version="1.0" encoding="UTF-8"?> but I want same <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>

1

1 Answers

1
votes

It is better to specify what is needed directly in XSLT.

You can try modified xsl:output as follows:

<xsl:output method="xml" indent="yes" standalone="no" encoding="ISO-8859-1" />