出力としてxmlファイルを書き込むJavaプログラムを書いています。現在、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);
助けていただければ幸いです。