Skip to Main Content

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

3901039Jan 6 2020 — edited Jan 7 2020

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("{http://xml.apache.org/xslt}indent-amount", "2");

            transformer.transform(xmlInput, new StreamResult(stringWriter));

            pretty                          = stringWriter.toString();

            pretty                          = pretty.replace("\r\n", "\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.
Comments
Post Details
Added on Jan 6 2020
2 comments
75 views