0

我有一个在 java 中手动生成的旧 xml 文件。它的树形结构是这样的。

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="tvshows.xsl"?>
<rss version='0.91'>
<channel>
<title>xyz.com</title>
<link>http://www.xyz.com</link>
<description></description>
<item>
<title>Downton Abbey</title>
<link>http://www.xyz.com</link>
<description><![CDATA[
<tr class='chartContent'>
<td class='rank'>1.</td>
<td class='showTitle'>Dexter</td>
<td class='network'>CBS</td>
<td class='sumInvIndex'>210</td>
<td class='earlierWeek'>-13</td>
<td class='mediaInvIndex'>225</td>
<td class='socialNetworkInvIndex'>238</td>
<td class='gammaIndex'>--</td>
</tr>]]>
</description>
</item>
</channel>
</rss>

现在正在使用 JDOM 库来生成确切的格式。但是我应该如何处理 CDATA[]。我发现 <tr> 有近 10 列。我正在尝试用

CDATA cdata = new CDATA("<tr class='chartContent'>");
cdata.append("<td class='rank'>" + current.getRank() + "</td>");
cdata.append("\n");
cdata.append("<td class='showTitle'>" + current.getShowTitle() + "</td>");
cdata.append("<td class='network'>" + current.getNetwork() + "</td>");
cdata.append("<td class='sumInvIndex'>" + current.getsumInvIndex() +"</td>");
cdata.append("<td class='earlierWeek'>" + current.getearlierWeek() + "</td>");
cdata.append("<td class='mediaInvIndex'>" + current.getmediaInvIndex() + "</td>");
cdata.append("<td class='socialNetworkInvIndex'>" + current.getsocialNetworkInvIndex() + "</td>");
cdata.append("<td class='gammaIndex'>" + current.getgammaIndex() + "</td>");
cdata.append("</tr>");

Element description = new Element("description");  
description.setContent(cdata);

但是是否有一种将标签附加到列的最佳方法,例如

Element rankTD = new Element("td");
rankTD.setText(current.getRank());
& add rankTD element to cdata .

使用后生成的输出

Format format = null;
format = Format.getPrettyFormat();
content.add(new Element("td").setText(current.getRank()).setAttribute("class","showTitle"));
-------------------
-------------------
-------------------
String cdataContent = new XMLOutputter(format).outputString(content);

输出:

<description><![CDATA[<tr class="chartContent" />
<td class="showTitle">1.</td>
<td class="network">PBS</td>
<td class="sumInvIndex">210</td>
<td class="earlierWeek">-13</td>
<td class="mediaInvIndex">225</td>
<td class="socialNetworkInvIndex">238</td>
<td class="gammaIndex">--</td>]]></description>
4

1 回答 1

1

您需要将该CDATA部分的内容String单独编码并将其String放入中CDATA,如下所示:

List<Element> content = new ArrayList<Element>();
content.add(new Element("td").setText(current.getRank());
...
String cdataContent = new XMLOutputter().outputString(content);
description.setContent(new CDATA(cdataContent));
于 2012-11-05T14:34:56.800 回答