如何将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="<root><first>01</first><second>02</second></root>"/>
答案 0 :(得分:2)
这是对的。在属性上设置时,应该转义xml。 如果你想看到普通的xml,你必须把它放在一个元素上并强制使用CDATA部分:
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");
CDATA部分不能用于属性...属性不是用于填充xml文档...