我正在尝试开发一项XML导出功能,以便让我的应用程序用户以XML格式导出他们的数据。我已经准备好并且该功能正常工作,直到它对某些情况开始失败。然后我意识到这是因为需要编码一些特殊字符。例如,数据可能包含&、!、%、'、#等等,这需要得到适当的转义。
我想知道是否有通用的实用程序可用,可以根据XML规范转义所有特殊字符。我在Google上找不到任何信息。
已经有这样的东西了吗?还是有其他方法可以处理这个问题?
这里是我用来生成XML的代码
Document xmldoc = new DocumentImpl();
Element root = xmldoc.createElement("Report");
Element name= xmldoc.createElement((exportData.getChartName() == null) ? "Report" : exportData.getChartName());
if (exportData.getExportDataList().size() > 0
&& exportData.getExportDataList().get(0) instanceof Vector) {
// First row is the HEADER, i.e name
Vector name = exportData.getExportDataList().get(0);
for (int i = 1; i value = exportData.getExportDataList().get(i);
Element sub_root = xmldoc.createElement("Data");
//I had to remove a for loop from here. StackOverflow description field would not take that. :(
// Insert header row
Element node = xmldoc.createElementNS(null, replaceUnrecognizedChars(name.get(j)));
Node node_value = xmldoc.createTextNode(value.get(j));
node.appendChild(node_value);
sub_root.appendChild(node);
chartName.appendChild(sub_root);
}
}
}
root.appendChild(name);
// Prepare the DOM document for writing
Source source = new DOMSource(root);
// Prepare the output file
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);`
示例 XML:
<Data>
<TimeStamp>2010-08-31 00:00:00.0</TimeStamp>
<[Name that needs to be encoded]>0.0</[Name that needs to be encoded]>
<Group_Average>1860.0</Group_Average>
</Data>