如何在不将内容转换为Java中的xml文件的情况下放置String文本?

时间:2011-03-31 13:44:06

标签: java xml string dom document

我需要在Java中将String内容放到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 &lt;b&gt;is&lt;/b&gt; 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文件中。

提前致谢!

5 个答案:

答案 0 :(得分:2)

这是预期的行为。

考虑是否在放置括号时保留括号,最终结果基本上是:

<cards>  
  <card>    
    <question>
      This 
      <b>
        is
      </b>
       a test.
    </question>  
  </card>
</cards>

基本上,它会导致<b>成为xml树中的附加节点。将括号编码为&lt;&gt;可确保在由任何xml解析器显示时,将显示括号,而不会将其混淆为附加节点。

如果真的希望它们按照您的说法显示,则需要创建名为b的元素。这不仅是笨拙的,它也不会像你上面所写的那样显示 - 它将显示为我上面所示的其他嵌套节点。因此,您需要修改xml编写器以为这些标记输出内联。

讨厌的。

答案 1 :(得分:1)

也许你可以用这种方式解决它(仅用于<question>标签部分的代码):

Element question = doc.createElement("question");
question.appendChild(doc.createTextNode("This ");
Element b = doc.createElement("b");
b.appendChild(doc.createTextNode("is");
question.appendChild(b);
question.appendChild(doc.createTextNode(" a test.");
card.appendChild(question);

答案 2 :(得分:1)

检查此解决方案:how to unescape XML in java

答案 3 :(得分:0)

您实际要做的是将XML插入到DOM的中间而不进行解析。你不能这样做,因为DOM API不支持它。

您有三种选择:

  • 您可以序列化DOM,然后在适当的位置插入String。最终结果可能是也可能不是格式良好的XML ...取决于您插入的字符串中的内容。

  • 您可以创建和插入表示文本和<b>...</b>元素的DOM节点。这需要您了解要插入的内容的XML结构。 @ bluish的回答举了一个例子。

  • 您可以将String包装在某个容器元素中,使用XML解析器解析它以提供第二个DOM,找到感兴趣的节点,并将它们添加到原始DOM中。这要求在包装在容器元素中时,String是格式良好的XML。

答案 4 :(得分:0)

或者,既然你已经在使用转型,为什么不一直走?

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output omit-xml-declaration="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<xsl:template match="cards">
    <card>
        <question>This <b>is</b> a test</question>
    </card>
</xsl:template>
</xsl:stylesheet>