Мне нужно поместить содержимое строки в XML на Java. Я использую этот вид кода для вставки информации в XML:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File ("file.xml"));
DOMSource source = new DOMSource (doc);
Node cards = doc.getElementsByTagName ("cards").item (0);
Element card = doc.createElement ("card");
cards.appendChild(card);
Element question = doc.createElement("question");
question.appendChild(doc.createTextNode("This <b>is</b> a test.");
card.appendChild (question);
StreamResult result = new StreamResult (new File (file));
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(source, result);
Но строка преобразуется в xml следующим образом:
<cards>
<card>
<question>This <b>is</b> a test.</question>
</card>
</cards>
Должно быть так:
<cards>
<card>
<question>This <b>is</b> a test.</question>
</card>
</cards>
Я пытался использовать метод CDDATA, но код выглядит так:
// I changed this code
question.appendChild(doc.createTextNode("This <b>is</b> a test.");
// to this
question.appendChild(doc.createCDATASection("This <b>is</b> a test.");
Этот код выглядит как XML-файл:
<cards>
<card>
<question><![CDATA[This <b>is</b> a test.]]></question>
</card>
</cards>
Я надеюсь, что кто-нибудь поможет мне поместить содержимое String в файл XML точно с таким же содержимым.
Заранее спасибо!