Java DOM setAttribute 不起作用

标签 java xml dom setattribute

有人可以告诉我为什么这不起作用吗?这让我发疯。

myFile.xml

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

Java代码

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.");
}

输出

oldValue
oldValue

无论我做什么,我都无法将代码写入 XML 文件...我尝试在根的子节点上执行 setAttribute() 函数。我尝试过删除 root...没有任何作用。我非常沮丧,所以任何帮助将不胜感激。谢谢。

最佳答案

您是否遵循与下面相同的代码?这对我有用(与 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.");
    }
}

关于Java DOM setAttribute 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064223/

相关文章:

java.io.FileNotFoundException/employee.xml : open failed ENOENT (No such file or directory) on file read

java - 无法从 java 文件 Intellij id 导入 proto 文件

java - 如何在 Java 中使用 ConnectionManager 终止 HttpConnection?

java - 在 Java 中使用百分比符号作为用户输入

java - 删除 xsi :type after marshalling abstract class with hierarchy

java - Xades4j验证封装签名

jquery - &lt;input/>类型转换(jQuery)

java - 如何在 RCP 应用程序/SWT 中实现超时

android - 如何在 Android 的 ListView 中放置图像和文本

javascript - DOM 创建表格但并非所有列都有单元格