【发布时间】:2011-03-31 13:44:06
【问题描述】:
我需要将字符串内容放入 Java 中的 xml。我使用这种代码在 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文件中,内容完全相同。
提前致谢!
【问题讨论】:
-
你确定你真的想在你的
b元素中包含一个b元素吗?任何实际读取question元素内容的内容都会按照您的意图看到文本,实体编码用于将其存储在 XML 数据中。例如,它所做的实际上是正确的,以后读取您的 XML 的任何内容都会得到文本“This is a test”。 -
@Crowder 是的,我确定。我使用 Java 程序创建了卡片组,其中包括带有问答部分的卡片。文本应使用 -tags 设置样式,以便可以在 Flash 中使用样式文本。在 java 程序中,我使用带有 html 内容的 JTextPane,所以我可以正确地看到它。
标签: java xml string dom document