0

I'm developing a game for a school project and i'd like to save the state of the game in a XML file.

At the moment I'm able to read the info's in the XML file but i can't update it and i don't know why...

Here is the XML:

<story>
  <level id="1">
    <text>Some info about the level...</text>
    <finished>false</finished>
    <nbsteps>0</nbsteps>
  </level>
</story>

I'd like to edit the <finished>false</finished> to <finished>true</finished> as the player finishes this level.

At the moment I've written that code to edit this but it's actually not editing the xml...

    public void updateSave(){
    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(this.xmlSave);

        Element racine = doc.getDocumentElement();
        NodeList levelList = doc.getElementsByTagName("level");
        Element niveau = (Element) levelList.item(this.levelId);
        niveau.getElementsByTagName("finished").item(0).setTextContent("true");


        }
        catch (ParserConfigurationException | SAXException | IOException | DOMException e) {}
    }

Thanks for the explanations and have a nice day!

DEEGROY
  • 17
  • 2
  • 2
    Your code **did** edit the xml, but didn't save it to the disk. You will have to save it somehow. – glee8e May 07 '17 at 10:38
  • Look at this: [http://stackoverflow.com/questions/4561734/how-to-save-parsed-and-changed-dom-document-in-xml-file](http://stackoverflow.com/questions/4561734/how-to-save-parsed-and-changed-dom-document-in-xml-file). – rjsperes May 07 '17 at 10:41
  • Thanks, it works now! – DEEGROY May 07 '17 at 11:07

1 Answers1

0

Okay thanks I only forgot to save ^^"

my definitive code, which works well is

    public void updateSave() throws TransformerConfigurationException, TransformerException{
    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(this.xmlSave);

        Element racine = doc.getDocumentElement();
        NodeList levelList = doc.getElementsByTagName("level");
        Element niveau = (Element) levelList.item(this.node.id);
        niveau.getElementsByTagName("finished").item(0).setTextContent("true");

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Result output = new StreamResult(this.xmlSave);

        Source input = new DOMSource(doc);
        transformer.transform(input, output);
        }
        catch (ParserConfigurationException | SAXException | IOException | DOMException e) {}
    }
DEEGROY
  • 17
  • 2