Forum Stats

  • 3,852,900 Users
  • 2,264,146 Discussions


Changing values in XML when looping not saving the new values on next loop

3901039 Member Posts: 1
edited Jan 7, 2020 7:53PM in Java Programming

Hey all I am having an issue with the code below due to me not being able to grasp what I am missing. I know the issue is that every call to searchXML() it just reads the original file that does not have the edits in it. But I am at a loss as to how to go about using the original and then not using the original since my attempt below does not seem to work....

static int X                        = 0;public static void main(String[] args) {    String[] tags = {"<!--D01-->:2000-12-08",                     "<!--D02-->:2010-01-02",                     "<!--D03-->:1990-02-29",                     "<!--D04-->:2015-09-12",                     "<!--D05-->:1996-04-04",                     "<!--D06-->:2002-05-22"};    try {        for (int i = 0; i < tags.length; i++) {            searchXML(tags[i], tags.length);        }    } catch (Exception e) {        e.printStackTrace();    }}public static void searchXML(String TAG, int MaxNumber) throws Exception {    Scanner input                           = null;    String modifiedXML                      = "";    String theText                          = "";    String currentLineValue                 = null;    // Split array into 2 separate values [0]xxxxx [1]zzzzz    String[] _tmpSplit                      = TAG.split(":");    if (i >= 1) {        //We've been around 1 or more times (load modified xml file)        input = new Scanner(new File("c:/temp/newXML.xml"));    } else {        //We've been around only 1 time (load original xml file)        input = new Scanner(new File("c:/temp/anotherxml.xml"));    }    while (input.hasNextLine()) {        currentLineValue                    = input.nextLine().trim();        currentLineValue                    = currentLineValue.replace("<!-- ", "<!--").replace(" -->", "-->");        if (currentLineValue.contains(_tmpSplit[0])) {            modifiedXML                     += currentLineValue + "\n";            currentLineValue                = input.nextLine();            //check if this is just a blank tag            int blankTag                    = currentLineValue.indexOf("</");            if (blankTag == -1) {                //Its blank so go to the next line                modifiedXML                 += currentLineValue + "\n";                //Now grab that new lines text (that we wanted originally)                currentLineValue            = input.nextLine();            }            //Check for the position number of where the > ends            theText                         = currentLineValue                                                .substring(currentLineValue                                                    .indexOf(">"),                                              currentLineValue                                                .indexOf("</"))                                                    .replace(">", "")                                                        .trim();            //Now replace the old value (_tmpSplit[1]) with the new value (theText).            currentLineValue                = currentLineValue.replace(theText, _tmpSplit[1]);        }        //Finally save the modified value (if...) or original value (else...)        modifiedXML                         += currentLineValue;    }    input.close();    X++;    //Format and save new XML to file if we reached X    if (MaxNumber == X) {        Scanner input                       = new StreamSource(new StringReader(modifiedXML));        StringWriter stringWriter           = new StringWriter();        String pretty                       = null;        try {            // Format the 1 row string XML we made into pretty line(s)/tab(s) xml            Transformer transformer         = TransformerFactory.newInstance().newTransformer();            transformer.setOutputProperty(OutputKeys.INDENT, "yes");            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");            transformer.setOutputProperty(OutputKeys.METHOD, "xml");            transformer.setOutputProperty("{}indent-amount", "2");            transformer.transform(xmlInput, new StreamResult(stringWriter));            pretty                          = stringWriter.toString();            pretty                          = pretty.replace("", "\n");                                } catch (Exception e) {            throw new RuntimeException(e);        }        // Write the new xml file        BufferedWriter writer               = new BufferedWriter(new FileWriter("c:/temp/newXML.xml"));        writer.write(pretty);        writer.flush();        writer.close();            }}anotherxml.xml = the main xml file that needs changes.newXML.xml = the new xml file that has the changes.

If someone here can wrap their head around this and let me know what I would need to do in order for it to..

  1.     Be able to read the old xml.
  2.     Loop through that to find the X number of replaceable values.
  3.     Save the new XML with that value.
  4.     Go to the next value we are looking for.
  5.     This time around it loads the modified xml.
  6.     repeat.


  • mNem
    mNem Member Posts: 1,380 Gold Trophy
    edited Jan 6, 2020 9:56AM

    As a suggestion, please post the class file that requires minimal effort from someone who may want to look into your issue - i.e. a class file that compiles and can be copy pasted. Additionally post all dependencies required and the expected result.

  • morgalr
    morgalr Member Posts: 457
    edited Jan 7, 2020 7:53PM

    I think you would have a lot better luck, reading a line, and then doing the mods you choose, then writing the line out to the new file so:

    read in

    mod or not

    write out

    loop until done

    rename the old file

    rename the new file

    close it all up

    Simple... is always better if it works just as well.