繁体   English   中英

使用Java修改xml版本

[英]Modify the xml version with java

将xml文件的版本从1.0更改为1.1的最佳方法是什么? 我需要使用dom解析它们,但是如果不将xml版本设置为1.1,就无法做到这一点,因为某些文件包含一些无效字符,而使用xml 1.0则无法接受。

我不知道如何构建这些文件,但是无论如何我还是得到了一些。

这些文件相当大,因此我不想仅更改标题就加载到整个文件。

我可以以某种方式修改File的InputStream或替换文件的标题而不加载整个内容吗?

DOM解析器将文件的整个内容加载到内存中,但是我认为您可以将regex和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) {

    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM