2

有人能告诉我为什么这不起作用吗?这让我疯狂。

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

4

2 回答 2

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.");
    }
}
于 2012-08-21T23:16:22.767 回答
1

您的代码只是写入 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();
      }
于 2015-07-03T11:21:21.380 回答