【问题标题】:Modify the xml version with java用java修改xml版本
【发布时间】:2015-02-11 14:05:29
【问题描述】:
将 xml 文件的版本从 1.0 更改为 1.1 的最佳方法是什么?
我需要使用 dom 解析它们,但如果不将 xml 版本设置为 1.1,我就无法做到这一点,因为某些文件有一些无效字符,使用 xml 1.0 不接受这些字符。
我不知道如何构建这些文件,但无论如何我得到了一些。
这些文件相当大,所以我不想加载到整个文件只是为了更改标题。
我可以在不加载整个内容的情况下以某种方式修改文件的 InputStream 或替换文件的标题吗?
【问题讨论】:
标签:
java
xml
file
inputstream
sax
【解决方案1】:
DOM 解析器将文件的全部内容加载到内存中,但我认为您可以结合使用正则表达式和RandomAccessFile 来获得所需的效果。试试下面的代码 sn -p:
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) {
}
}