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?

4
  • What is expected here? The element attributes are being changed. Do you want to save them back in the XML? Commented Jan 8, 2015 at 19:34
  • Yes, my UI allows users to change the value, so I am setting the new value in the xml. Commented Jan 8, 2015 at 19:40
  • How are you verifying that the attributes were or were not changed? Commented Jan 8, 2015 at 19:45
  • 1
    Take a look at: stackoverflow.com/questions/20052871/… Commented Jan 8, 2015 at 19:48

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.