错误更改xml节点中的值

时间:2016-11-09 03:59:52

标签: java xml jdom

我需要更改xml的几个值,但是当我运行.setText行时,它会显示java.lang.NullPointerException错误,我不明白为什么。

<?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>

这是代码:

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

问候和感谢。

1 个答案:

答案 0 :(得分:2)

let newTrainees = data?["data"].arrayValue.map({ (json) in return FutureTrainee(data: json) }) let trainees = self.futureTraineeCollection.futureTrainees + newTrainees

这看起来不错。 desc是属性,而不是孩子,对吧?

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