Menu Home

Java DOM 设置XML STANDALONE

    public void save2file() {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(mDocument);

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

            PrintWriter pw = new PrintWriter(new FileOutputStream(mFileName));
            StreamResult result = new StreamResult(pw);
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出:

 <?xml version="1.0" encoding="utf-8" standalone="no"?>

这里的 transformer.setOutputProperty(OutputKeys.STANDALONE, “yes”);居然不起效!

GOOGLE了一通,加了一行mDocument.setXmlStandalone(true);,变成了下面的代码:

    public void save2file() {
            mDocument.setXmlStandalone(true);
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(mDocument);

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

            PrintWriter pw = new PrintWriter(new FileOutputStream(mFileName));
            StreamResult result = new StreamResult(pw);
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

输出结果是正确了,但还没空搞清楚为啥( ⊙ o ⊙ )

Categories: java xml

Tagged as:

lnmcc

Leave a Reply

Your email address will not be published.