How to indent XML properly using XMLSerializer?

前端 未结 4 1318
野性不改
野性不改 2021-02-07 14:39

I\'m having a hard time trying to indent XML files using XMLSerializer.

I\'ve tried

serializer.setFeature(\"http://xmlpull.org/v1/doc/featur         


        
4条回答
  •  逝去的感伤
    2021-02-07 15:04

    This is a solution in Java, andriod does support transformer so this should work.

    // import additional packages
    import java.io.*;
    
    // import DOM related classes
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    
    // write the output file
    try {
      // create a transformer
      TransformerFactory transFactory = TransformerFactory.newInstance();
      Transformer        transformer  = transFactory.newTransformer();
    
      // set some options on the transformer
      transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    
      // get a transformer and supporting classes
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      DOMSource    source = new DOMSource(xmlDoc);
    
      // transform the xml document into a string
      transformer.transform(source, result);
    
      // open the output file
      FileWriter outputWriter = new FileWriter(outputFile);
      outputWriter.write(writer.toString());
      outputWriter.close();
    
    } catch(javax.xml.transform.TransformerException e) {
      // do something with this error
    }catch (java.io.IOException ex) {
      // do something with this error
    }
    

提交回复
热议问题