我有一个xml文件,它的结构是这样的。
<?xml version="1.0" encoding="MS949"?>
<pmd-cpd>
<duplication lines="123" tokens"123">
<file line="1" path="..">
<file line="1" path="..">
<codefragment><![CDATA[........]]></codefragment>
</duplication>
<duplication>
...
</duplication>
</pmd-cpd>
我想删除“codefragment”节点,因为我的解析器出错“无效的 XML 字符(0x1)”。 '
我的解析代码是这样的,
private void parseXML(File f){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(f);
}catch(...)
错误发生在 document = builder.parse(f);
中,因此我无法使用解析器删除 codefragment
节点。
这就是为什么我想在没有解析器的情况下删除这些行。
如何在没有解析器的情况下删除此节点...?
最佳答案
这是对OP self 回答的后续回答,以及我对该回答的评论。这是回顾,加上一些额外的内容:
- 切勿在循环中执行
String += String
。使用StringBuilder
。 - 以 block 而非行的形式读取 XML。
- 不要使用
String.replaceAll()
。它必须每次都重新编译正则表达式,这是您已经拥有的正则表达式。使用Matcher.replaceAll()
。 - 请记住
close()
Reader。更好的是,使用try-with-resources
。 - 无需将干净的 XML 保存回来,直接使用即可。
- 由于 XML通常采用 UTF-8 格式,因此请以 UTF-8 格式读取文件。
- 不要打印并忽略错误。让调用者处理错误。
private static void parseXML(File f) throws IOException, ParserConfigurationException, SAXException {
StringBuilder xml = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f),
StandardCharsets.UTF_8))) {
Pattern badChars = Pattern.compile("[^\\u0009\\u000a\\u000d\\u0020-\\uD7FF\\uE000-\\uFFFD]+");
char[] cbuf = new char[1024];
for (int len; (len = in.read(cbuf)) != -1; )
xml.append(badChars.matcher(CharBuffer.wrap(cbuf, 0, len)).replaceAll(""));
}
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document document = domBuilder.parse(new InputSource(new StringReader(xml.toString())));
// insert code using DOM here
}
关于JAVA如何查找和删除句子结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33953177/