DOMImplementationLS serialize to String in UTF-8 in Java

后端 未结 2 1634
醉梦人生
醉梦人生 2021-01-04 04:58

reading the documentation for java org.w3c.dom.ls it seems as a Element only can be serialized to a String with the java native string encoding, UTF-16. I need however to cr

相关标签:
2条回答
  • 2021-01-04 05:51

    You can still use DOMImplementationLS:

    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.
    DOMImplementationLS domImplementationLS = (DOMImplementationLS)REGISTRY.getDOMImplementation("LS");
    LSOutput lsOutput =  domImplementationLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(doc, lsOutput);     
    String result = stringWriter.toString();
    
    0 讨论(0)
  • 2021-01-04 05:55

    I find that the most flexible way of serializing a DOM to String is to use the javax.xml.transform API:

        Node node = ...
        StringWriter output = new StringWriter();
    
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(node), new StreamResult(output));
    
        String xml = output.toString();
    

    It's not especially elegant, but it should give you better control over output encoding.

    0 讨论(0)
提交回复
热议问题