Java DOM setAttribute не работает

Может кто-нибудь сказать мне, почему это не работает? Это сводит меня с ума.

мой файл.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... Ничего не работает. Я вне разочарования, поэтому любая помощь будет оценена по достоинству. Спасибо.


person Joey Mason    schedule 21.08.2012    source источник
comment
У меня точно такая же проблема. У кого-нибудь есть решение для этого?   -  person JoshMachine    schedule 04.03.2013


Ответы (2)


Вы следуете тому же коду, что и ниже? Это работает для меня (с тем же содержимым в 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.");
    }
}
person Kevin Mangold    schedule 21.08.2012
comment
Просто для удовольствия, какую версию Java вы используете? - person Kevin Mangold; 22.08.2012
comment
Да, я следую тому же коду. Вот почему это так расстраивает. Я знаю, что он может получить доступ к файлу, потому что он может читать его нормально. Он просто не может писать в него. У меня 1.5_012 - person Joey Mason; 22.08.2012

Ваш код просто записывался в объект 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();
      }
person alanj853    schedule 03.07.2015