Java DOM setAttribute不起作用

时间:2012-08-21 22:57:53

标签: 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文件......我尝试在root的子节点上执行setAttribute()函数。我试过删除root ...什么都行不通。我非常沮丧,所以任何帮助都会受到赞赏。感谢。

2 个答案:

答案 0 :(得分: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.");
    }
}

答案 1 :(得分: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();
      }