将xml存储到xml属性中

时间:2015-01-12 17:50:35

标签: java xml

如何将xml文档存储到xml属性中?我有这个代码,但de输出给我转义字符,右边是这些转义符吗?

public static void main(String[] args) throws TransformerException,
    ParserConfigurationException  {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element organizations = doc.createElement("ORGANIZATIONS");
        doc.appendChild(organizations);
        organizations.setAttribute("xml", "<root><first>01</first><second>02</second></root>");
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        StreamResult sr = new StreamResult(new File("test.xml"));

        transformer.transform(domSource, sr);

    }

输出:

<ORGANIZATIONS xml="&lt;root&gt;&lt;first&gt;01&lt;/first&gt;&lt;second&gt;02&lt;/second&gt;&lt;/root&gt;"/>

1 个答案:

答案 0 :(得分:2)

这是对的。在属性上设置时,应该转义xml。 如果你想看到普通的xml,你必须把它放在一个元素上并强制使用CDATA部分:

transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");

CDATA部分不能用于属性...属性不是用于填充xml文档...