Error change values in node of a xml

时光毁灭记忆、已成空白 提交于 2020-01-04 14:00:59

问题


I need to change several values of an xml, but when I run the line .setText, it shows the java.lang.NullPointerException error and I do not understand why.

<?xml version="1.0" encoding="UTF-8"?>
<prueba>
 <reg id="576340">
   <dato cant="680" id="1" val="-1" num="" desc="" />
   <dato cant="684" id="5" val="-1" num="" desc="" />
   <dato cant="1621" id="1" val="-1" num="" desc="Hi" />
   <dato cant="1625" id="5" val="-1" num="" desc="Hola" />  
 </reg>
</prueba>

This is the code:

 public static void main(String[] args) throws FileNotFoundException, 
 JDOMException, IOException {

    File xml = new File("c:\\prueba3.xml");
    XMLOutputter xmlOut = new XMLOutputter();
    Document doc = (Document) new SAXBuilder().build(xml);
    Element raiz = doc.getRootElement();
    List articleRow = raiz.getChildren("reg"); 

    for (int i = 0; i < articleRow.size(); i++) {

        Element row = (Element) articleRow.get(i);
        List images = row.getChildren("dato");

         for (int j = 0; j < images.size(); j++) {

             Element row2 = (Element) images.get(j);
             String texto = row2.getAttributeValue("desc") ;
             String id = row2.getAttributeValue("id"); 

             if ((texto != null) && (texto !="") && 
                (id.equals("1") || id.equals("2"))){
                     row2.getChild("desc").setText("valor");
             }
         }
    }
     xmlOut.setFormat(Format.getPrettyFormat());
     xmlOut.output(doc, new FileWriter("c:\\prueba3.xml"));
     System.out.println("fin");  
}

Greetings and thanks.


回答1:


row2.getChild("desc").setText("valor");

This looks wrong. desc is an attribute, not a child, right?

It should be row2.getAttributeNode("desc").setValue("valor")



来源:https://stackoverflow.com/questions/40500027/error-change-values-in-node-of-a-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!