gpt4 book ai didi

java - 将 xml 存储到 xml 属性中

转载 作者:行者123 更新时间:2023-11-30 03:35:52 25 4
gpt4 key购买 nike

如何将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com