我有一个名为test.xml
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root>
<user id="1">
<firstname>James</firstname>
<lastname>John</lastname>
</user>
</root>
我有一个完美运行的简单java程序
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());
}
}
输出:
Old id value: 1
New id value: 2
不幸的是,当我去检查我的xml文件时,我发现没有任何变化。
这与read-only
文件或类似内容有关吗?我该如何解决这个问题?