2016-11-09 4 views
2

XML의 여러 값을 변경해야하지만 .setText 행을 실행하면 java.lang.NullPointerException 오류가 표시되고 이유를 이해할 수 없습니다.xml 노드의 오류 변경 값

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

인사와 감사 :

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

는 코드입니다.

+0

kaitoy의 대답이 정확한지 @row2.getAttributeNode("desc").setValue("valor"), 그것은 row2.getAttribute ("DESC")해야해야 setValue의 ("용맹."); – Waqas

+0

row2.getAttribute ("desc")를 사용합니다. setValue ("valor"); 불편을 끼쳐 드려 죄송합니다. 인사드립니다. –

답변

2

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

잘못된 것처럼 보입니다. desc는 자식이 아닌 특성입니다. 맞습니까?