我正在编写一个java程序,它将xml文件写为输出。现在,xml中有一些节点值包含实体引用,如<,>,'和“。当前输出是这样的:
<Parent>
<Child><'"</Child>
</Parent>
我需要输出:
<Parent>
<Child><'"</Child>
</Parent>
我在下面的帖子中读到可能无法做我想要的事情: StAX XML Parser not escaping single quote (')
但是读取此xml文件的系统需要转义所有引号和撇号。我怎样才能做到这一点?
一些代码:
DocumentBuilderFactory coDocFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder coDocBuilder = coDocFactory.newDocumentBuilder();
coXMLDocument = coDocBuilder.newDocument();
Element coParent = coXMLDocument.createElement("Parent");
coXMLDocument.appendChild(coParent);
Element coChild = coXMLDocument.createElement("Child");
coParent.appendChild(coChild);
coChild.setTextContent("<>/'/""); //apostrophe and quotes have been escaped
TransformerFactory coTransFactory = TransformerFactory.newInstance();
Transformer transformer = coTransFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource coDomSource = new DOMSource(coXMLDocument);
StreamResult coResult = new StreamResult(new File("C:\\a.xml"));
transformer.transform(coDomSource, coResult);
帮助将不胜感激。