Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the xml version with java

What is the best way to change the version of an xml file from 1.0 to 1.1? I need to parse them using dom, but I cannot do that without setting the xml version to 1.1, because some files have some invalid characters which are not accepted using xml 1.0.

I don't know how these files could be built, but anyway I got some.

These Files are rather big, so I wouldn't like to load to whole file only to change the header.

Can I somehow modify the InputStream of the File or replace the header of the file without loading the whole content?

like image 840
Jayni Avatar asked Sep 02 '25 16:09

Jayni


1 Answers

The DOM parser loads the whole content of a file into memory, but I think you can combine usage of regex and RandomAccessFile to get the desired effect. Try the following code snippet:

    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) {

    }


}
like image 108
Kuba Rakoczy Avatar answered Sep 05 '25 07:09

Kuba Rakoczy