Joey Mason
Joey Mason

Reputation: 707

Java DOM setAttribute not working

Can someone tell me why this isn't work? It's driving me crazy.

myFile.xml

<?xml version="1.0" encoding="UTF-8" ?>
<root date="oldValue" />     

Java Code

try {
    Document doc = builder.parse(new File("myFile.xml"));
    Element root = doc.getDocumentElement();
    System.out.println("date: " + root.getAttribute("date") + "\n");
    root.setAttribute("date", "test");
    System.out.println("date: " + root.getAttribute("date"));
}  catch (Exception e)  {
    System.out.println("Something went wrong.");
}

Output

oldValue
oldValue

No matter what I do, I cannot get my code to write to the XML file... I've tried performing the setAttribute() function on child nodes of the root. I've tried just removing root... Nothing works. I'm beyond frustrated, so any help would be appreciated. Thanks.

Upvotes: 2

Views: 4843

Answers (2)

alanj853
alanj853

Reputation: 11

Your code was just writing to the Element object, as opposed to the .xml file (However, when I ran your code my output was:

             date: oldValue

             date: test

To write to the .xml file, use the following.

try
      {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File("myFile.xml"));

        Element root = doc.getDocumentElement();
        System.out.println("date: " + root.getAttribute("date") + "\n");
        root.setAttribute("date", "test");

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("myFile.xml"));
        transformer.transform(source, result);


        System.out.println("date: " + root.getAttribute("date"));

      }
    catch (TransformerException | SAXException | ParserConfigurationException | IOException e )
      {
        System.out.println("Something went wrong");
        e.printStackTrace();
      }

Upvotes: 1

Kevin Mangold
Kevin Mangold

Reputation: 1155

Are you following the same code as below? This works for me (with the same content in myFile.xml):

public static void main(String... args) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    try{
        Document doc = builder.parse(new File("myFile.xml"));
        Element root = doc.getDocumentElement();
        System.out.println("date: " + root.getAttribute("date") + "\n");
        root.setAttribute("date", "test");
        System.out.println("date: " + root.getAttribute("date"));
    } catch (Exception e) {
        System.out.println("Something went wrong.");
    }
}

Upvotes: 1

Related Questions