0

I have this xml file named test.xml

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root>
    <user id="1">
        <firstname>James</firstname>
        <lastname>John</lastname>
    </user>
</root>

And i have this simple java program which runs perfectly

package xmlParser;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class ParsingXml {

    public static void main(String[] args) throws SAXException, IOException,
            ParserConfigurationException {
        String filepath = "test.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);


        // Get the user element by tag name directly
        Node user = doc.getElementsByTagName("user").item(0);

        // update user id attribute
        NamedNodeMap attr = user.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        System.out.println("Old id value: "+nodeAttr.getTextContent());
        nodeAttr.setTextContent("2");
        System.out.println("New id value: "+nodeAttr.getTextContent());
    }

}

Output:

Old id value: 1
New id value: 2

Unfortunately when i go to check my xml file, i find no changes.

Is this related to read-only file or something like that? How can i solve this problem?

MChaker
  • 2,610
  • 2
  • 22
  • 38
  • Does `.setTextContent` actually save the updates or do you need to save after the text is updated? – NendoTaka May 21 '15 at 16:53
  • 1
    Save after updating the text @NendoTaka – MChaker May 21 '15 at 16:54
  • If you have to save after updating the text you need to add the code to save the file. I don't see any code to save your file above. – NendoTaka May 21 '15 at 17:04
  • @NendoTaka Yes you are right. I thought when calling `setTextContent` it will save the xml file. And [this](http://stackoverflow.com/questions/4561734/how-to-save-parsed-and-changed-dom-document-in-xml-file) solved my problem. – MChaker May 21 '15 at 17:09

0 Answers0