代码之家  ›  专栏  ›  技术社区  ›  xetra11

如何实际使用Java文档生成器的文档

  •  0
  • xetra11  · 技术社区  · 5 年前

    我已经摆弄了20多分钟,我的google foo让我失望了。

    假设我在Java中创建了一个XML文档(Or.W3C.DOM.DATA):

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document document = docBuilder.newDocument();
    
    Element rootElement = document.createElement("RootElement");
    Element childElement = document.createElement("ChildElement");
    childElement.appendChild(document.createTextNode("Child Text"));
    rootElement.appendChild(childElement);
    
    document.appendChild(rootElement);
    
    String documentConvertedToString = "?" // <---- How?
    

    如何将文档对象转换为文本字符串?

    0 回复  |  直到 7 年前
        1
  •  98
  •   Bozho    14 年前
    public static String toString(Document doc) {
        try {
            StringWriter sw = new StringWriter();
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    
            transformer.transform(new DOMSource(doc), new StreamResult(sw));
            return sw.toString();
        } catch (Exception ex) {
            throw new RuntimeException("Error converting to String", ex);
        }
    }
    
        2
  •  9
  •   XpiritO    14 年前

    您可以使用这段代码来完成您想要的:

    public static String getStringFromDocument(Document doc) throws TransformerException {
        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);
        return writer.toString();
    }