在Java中生成XML时转义特殊字符

Sal*_*gzi 30 java xml special-characters

我正在尝试开发XML导出功能,以便我的应用程序用户以XML格式导出他们的数据.我已经准备好这个功能,直到它开始失败了一些情况.然后我意识到这是因为需要编码的一些特殊字符.例如,数据可能包含&或!或%或'或#等等,这需要妥善转义.我想知道是否有可用的通用实用程序可以根据XML规范转义所有特殊字符.我在谷歌上找不到任何东西.

那里有类似的东西吗?或者还有其他办法吗?

这是我用来生成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);`
Run Code Online (Sandbox Code Playgroud)

示例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>
Run Code Online (Sandbox Code Playgroud)

gig*_*dot 52

您可以使用apache常见的lang库来转义字符串.

org.apache.commons.lang.StringEscapeUtils

String escapedXml = StringEscapeUtils.escapeXml("the data might contain & or ! or % or ' or # etc");
Run Code Online (Sandbox Code Playgroud)

但是,您正在寻找的是将任何字符串转换为有效的XML标记名称的方法.对于ASCII字符,XML标记名称必须以_:a-zA-Z之一开头,后跟_中的任意数量的字符:a-zA-Z0-9.-

我当然相信没有库可以为你做这个,所以你必须实现自己的函数来转换任何字符串以匹配这个模式,或者将它变成attritbue的值.

<property name="no more need to be encoded, it should be handled by XML library">0.0</property>
Run Code Online (Sandbox Code Playgroud)

  • 根据W3C for XML标准,可以使用有限数量的字符作为元素标记.您可能希望创建一个通用节点并将标头添加为属性的值,例如<data title ="现在可以是任何东西"/> (2认同)