有没有比这个代码更优雅的方法将XML文档转换为Java中的String?

时间:2008-11-24 21:21:30

标签: java xml

以下是目前使用的代码。

public String getStringFromDoc(org.w3c.dom.Document doc)    {
        try
        {
           DOMSource domSource = new DOMSource(doc);
           StringWriter writer = new StringWriter();
           StreamResult result = new StreamResult(writer);
           TransformerFactory tf = TransformerFactory.newInstance();
           Transformer transformer = tf.newTransformer();
           transformer.transform(domSource, result);
           writer.flush();
           return writer.toString();
        }
        catch(TransformerException ex)
        {
           ex.printStackTrace();
           return null;
        }
    }

4 个答案:

答案 0 :(得分:80)

依赖于DOM Level3 Load/Save

public String getStringFromDoc(org.w3c.dom.Document doc)    {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);   
}

答案 1 :(得分:13)

这更简洁:

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;
}

否则你可以使用像Apache的XMLSerializer这样的库:

//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());

答案 2 :(得分:12)

变换器API是从DOM对象转换为序列化形式(在本例中为String)的唯一XML标准方法。作为标准,我的意思是SUN Java XML API for XML Processing

其他替代方法(如Xerces XMLSerializer或JDOM XMLOutputter)是更直接的方法(代码更少),但它们是特定于框架的。

在我看来,你使用的方式是最优雅,最便携的。通过使用标准XML Java API,您可以在不更改代码的情况下插入您选择的XML-Parser或XML-Transformer(与JDBC驱动程序相同)。还有比这更优雅的东西吗?

答案 3 :(得分:8)

您可以使用XOM来执行此操作:

org.w3c.dom.Document domDocument = ...;
nu.xom.Document xomDocument = 
    nu.xom.converters.DOMConverter.convert(domDocument);
String xml = xomDocument.toXML();