Search code examples
javaxmleditfilewriter

Edit a XML file in java


I have the following XML file:

<Tables>
    <table>
        <row></row>
    </table>
<Tables>

and I want to edit it to :

<Tables>
    <table>
        <row>some value</row>
    </table>
<Tables>

I write the XML file using file writer. How can I edit it?

What I was found that I create a temp file contains edits then delete the original file and rename the temp file. Is there any other way?

that's my code to write the file:

public boolean createTable(String path, String name, String[] properties) throws IOException {
    FileWriter writer = new FileWriter(path);
    writer.write("<Tables>");
    writer.write("\t<" + name + ">");
    for(int i=0; i<properties.length; i++){
        writer.write("\t\t<" + properties[0] + "></" + properties[0] + ">");
    }
    writer.write("\t</" + name + ">");
    writer.write("</Tables>");
    writer.close();
    return false;
}

Solution

  • if your xml is static you can use this, here input.xml is your xml file

    File file = new File("input.xml");
    byte[] data;
    try (FileInputStream fis = new FileInputStream(file)) {
       data = new byte[(int) file.length()];
        fis.read(data);
    }
    String input = new String(data, "UTF-8");
    String tag = "<row>";
    String newXML = input.substring(0, input.indexOf(tag) + tag.length()) + "your value" + input.substring(input.indexOf(tag) + tag.length(), input.length());
    try (FileWriter fw = new FileWriter(file)) {
        fw.write(newXML);
    }
    System.out.println("XML Updated");