如何将 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="<root><first>01</first><second>02</second></root>"/>
最佳答案
这是正确的。在属性上设置时,应对 xml 进行转义。 如果您想查看纯 xml,则必须将其放在元素上并强制使用 CDATA 部分:
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");
CDATA 部分不能用于属性...属性不是为了填充 xml 文档而创建的...
关于java - 将 xml 存储到 xml 属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27907914/