5

作为一项特殊要求,我一直在尝试"使用.\"XMLDOM

不幸的是,当我用 编写文本时Document.createTextNode(TextValue),它会输出\". 然而,预期是\"

细节:

写入文本值:

    public static boolean setDOMElementValue(Document doc, Element elem, String nodeValue) {
    try {
        elem.appendChild(doc.createTextNode(nodeValue));
        return true;
    } catch (DOMException ex) {
        LOG.log(Level.SEVERE, ex.toString());
        return false;
    }
}

编写 XML:

    public static boolean writeDOMToXML(Document doc, String xmlFilePath) {
    try {
        doc.setXmlStandalone(true);
        // write content into xml file

        // Creating TransformerFactory and Transformer
        Transformer tr = TransformerFactory.newInstance().newTransformer();
        // Setting Transformer's output properties
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        tr.setOutputProperty(OutputKeys.METHOD, "xml");
        tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tr.setOutputProperty(OutputKeys.STANDALONE, "no");

        // Setting DOMSource and StreamResult
        DOMSource source = new DOMSource(doc);
        File file = new File(xmlFilePath);
        StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(file)));

        // Transform and Return
        tr.transform(source, result);
        return true;
    } catch (TransformerFactoryConfigurationError | TransformerConfigurationException ex) {
        LOG.log(Level.SEVERE, ex.toString());

        return false;
    } catch (TransformerException | FileNotFoundException ex) {
        LOG.log(Level.SEVERE, ex.toString());
        return false;
    }
}
4

1 回答 1

0

When you build a text node with the DOM, you should simply put in any string in there literally e.g. doc.createTextNode("\""). When you serialize the DOM tree the serializer will take care of escaping any character as needed (but within a text node there is no need to escape a double or single quote, that is only necessary inside an attribute value, depending on the attribute value delimiter).

于 2013-11-07T14:00:45.573 回答