2016-11-09 3 views
2

Мне нужно изменить несколько значений xml, но когда я запускаю строку .setText, она показывает ошибку java.lang.NullPointerException, и я не понимаю, почему.Значения изменения ошибки в узле xml

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

Привет и спасибо.

+0

@ ответ kaitoy является правильным, оно должно быть row2.getAttribute ("убывание") SetValue ("Доблесть"). – Waqas

+0

С row2.getAttribute ("desc"). SetValue ("valor"); Извините за неудобства приветствия. –

ответ

2

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

Это выглядит неправильно. desc - это атрибут, а не ребенок, правильно?

Это должно быть row2.getAttributeNode("desc").setValue("valor")

Смежные вопросы