0

I am not too sure why i cannot modify an attribute to my xml. The code below i used to get the read the attributes from the XML. Pulls the attributes without any issues.

        document = documentBuilder.parse(file);
        NodeList sessionNodelist = document.getElementsByTagName("session");
        if (sessionNodelist.getLength() > 0)
        {
            Element sessionElement = (Element) sessionNodelist.item(0);
            String timeout = sessionElement.getAttribute("timeout");
            String warning = sessionElement.getAttribute("warning");
        }

Now when i go to set them, it doesn't work and I am not too sure why. The code is below. it's the exact same code i used to pull the atribles, but instead of the getAttribute i used setAttribute which takes two parameters. setAttribute(String name, String Value).

        document = documentBuilder.parse(file);
        NodeList sessionNodelist = document.getElementsByTagName("session");
        if (sessionNodelist.getLength() > 0)
        {
            Element sessionElement = (Element) sessionNodelist.item(0);
            sessionElement.setAttribute("timeout","12");
            sessionElement.setAttribute("warning", "10");
        }

Any ideas?

M A
  • 71,713
  • 13
  • 134
  • 174
user1158745
  • 2,402
  • 9
  • 41
  • 60

1 Answers1

0

You need to write the document tree back to the XML file. See this page for how to write a DOM tree to a file.

You would use a javax.xml.transform.Transformer to write the object into the file as follows:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
M A
  • 71,713
  • 13
  • 134
  • 174
  • Last question, for somereason when i go to write the file path it doesn't like the fact that there is a space within program files. Any way to get around this? I am using escape chars E.g "C:\\Progarm Files\\test.xml" – user1158745 Jan 08 '15 at 20:32