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

DOM を使用してテキスト ノードを作成するときは、そこに任意の文字列をそのまま入力する必要があります (例: doc.createTextNode("\""). DOM ツリーをシリアライズすると、シリアライザーは必要に応じて任意の文字をエスケープします (ただし、テキスト ノード内では、二重引用符または単一引用符をエスケープする必要はありません。これは、属性値の区切り文字に応じて、属性値内でのみ必要です) )。

于 2013-11-07T14:00:45.573 に答える