将 xml 文件的版本从 1.0 更改为 1.1 的最佳方法是什么? 我需要使用 dom 解析它们,但如果不将 xml 版本设置为 1.1,我将无法做到这一点,因为某些文件包含一些无效字符,这些字符无法使用 xml 1.0 接受。
我不知道如何构建这些文件,但无论如何我得到了一些。
这些文件相当大,所以我不想加载整个文件只是为了更改标题。
我能否以某种方式修改文件的 InputStream 或替换文件头而不加载全部内容?
最佳答案
DOM 解析器将文件的全部内容加载到内存中,但我认为您可以结合使用正则表达式和 RandomAccessFile
以获得所需的效果。试试下面的代码片段:
String line, filepath = "/file.xml";
long ptr;
try (RandomAccessFile file = new RandomAccessFile(filepath, "rw");) {
//captures the XML declaration
Pattern p = Pattern
.compile("<\\?xml([^<>]*)version=\"(1.[01])\"([^<>]*)>");
//sets ptr to the beginning of a file
ptr = file.getFilePointer();
while ((line = file.readLine()) != null) {
Matcher m = p.matcher(line);
//if the xml declaration has been found
if (m.find()) {
String newLine = line.replace("version=\"1.0\"", "version=\"1.1\"");
file.seek(ptr);
file.write(newLine.getBytes());
break;
}
ptr = file.getFilePointer();
}
} catch (IOException ex) {
}
}
关于java - 用java修改xml版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27450808/