java - 将 xml 存储到 xml 属性中

标签 java xml

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

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;"/>

最佳答案

这是正确的。在属性上设置时,应对 xml 进行转义。 如果您想查看纯 xml,则必须将其放在元素上并强制使用 CDATA 部分:

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

CDATA 部分不能用于属性...属性不是为了填充 xml 文档而创建的...

关于java - 将 xml 存储到 xml 属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27907914/

相关文章:

java - "Java Concurrency In Practice"仍然有效吗?

java - 如何实现 Trip Advisor API 来获取特定酒店的评级和评论

Java动态重定义方法

java - 使用 JAXB 解码 XML 时出现 ClassCastException

php - 问答: Ex- and Import Database values with more than 1 Table in XML

java - 如何将菜单项添加到现有的 Android 应用程序菜单?

java - 新的二进制 XML 文件行 #19 : Error inflating class activity

java - 使用java检查十进制数顺序的逻辑

java - 将大 JSON 文件转换为 XML

xml - Xpath:使用 local-name() 选择节点值