tkj*_*kja 5 java xml unicode dom sax
我正在解析包含数字字符实体字符的 XML,例如(但不限于) < >
(换行回车 < >)在 Java 中。在解析时,我将节点的文本内容附加到 StringBuffer 以便稍后将其写入文本文件。
但是,当我将字符串写入文件或打印出来时,这些 unicode 字符会被解析或转换为换行符/空格。
在 Java 中迭代 XML 文件的节点并将文本内容节点存储到字符串时,如何保留原始数字字符实体字符符号?
演示 xml 文件示例:
<?xml version="1.0" encoding="UTF-8"?>
<ABCD version="2">
<Field attributeWithChar="A string followed by special symbols " />
</ABCD>
Run Code Online (Sandbox Code Playgroud)
示例 Java 代码。它加载 XML,遍历节点并将每个节点的文本内容收集到 StringBuffer。迭代结束后,它将 StringBuffer 写入控制台并写入文件(但没有
)符号。
将它们存储到字符串时,保留这些符号的方法是什么?请你帮助我好吗?谢谢你。
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
Document document = null;
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
document = documentBuilder.parse(new File("path/to/demo.xml"));
StringBuilder sb = new StringBuilder();
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap nnp = node.getAttributes();
for (int j = 0; j < nnp.getLength(); j++) {
sb.append(nnp.item(j).getTextContent());
}
}
}
System.out.println(sb.toString());
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("path/to/demo_output.xml"), "UTF-8"))) {
writer.write(sb.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
在将文件解析为Document
. 您可以通过使用其相应的 XML 实体对& 符号 本身进行转义来实现这一点。就像是,&
&
DocumentBuilder documentBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
String xmlContents = new String(Files.readAllBytes(Paths.get("demo.xml")), "UTF-8");
Document document = documentBuilder.parse(
new InputSource(new StringReader(xmlContents.replaceAll("&", "&"))
));
Run Code Online (Sandbox Code Playgroud)
输出 :
2A string followed by special symbols
Run Code Online (Sandbox Code Playgroud)