Is there a more elegant way to convert an XML Document to a String in Java than this code?

后端 未结 4 1714
轮回少年
轮回少年 2020-11-29 18:42

Here is the code currently used.

public String getStringFromDoc(org.w3c.dom.Document doc)    {
        try
        {
           DOMSource domSource = new DOM         


        
4条回答
  •  余生分开走
    2020-11-29 19:24

    This is a little more concise:

    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch(TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
    

    Otherwise you could use a library like XMLSerializer from Apache:

    //Serialize DOM
    OutputFormat format    = new OutputFormat (doc); 
    // as a String
    StringWriter stringOut = new StringWriter ();    
    XMLSerializer serial   = new XMLSerializer (stringOut,format);
    serial.serialize(doc);
    // Display the XML
    System.out.println(stringOut.toString());
    

提交回复
热议问题