【问题标题】:Java DOM setAttribute not workingJava DOM setAttribute 不起作用
【发布时间】:2012-08-21 22:57:53
【问题描述】:

谁能告诉我为什么这不起作用?快把我逼疯了。

我的文件.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() 函数。我试过只是删除根......没有任何效果。我非常沮丧,所以任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 我有完全相同的问题。有没有人可以解决这个问题?

标签: java xml dom setattribute


【解决方案1】:

您是否遵循与以下相同的代码?这对我有用(在 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?
  • 是的,我遵循相同的代码。这就是为什么它如此令人沮丧。我知道它能够访问该文件,因为它可以很好地读取它。它只是无法写入它。我正在运行 1.5_012
【解决方案2】:

您的代码只是写入 Element 对象,而不是 .xml 文件(但是,当我运行您的代码时,我的输出是:

             date: oldValue

             date: test

要写入 .xml 文件,请使用以下命令。

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();
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-15
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多