xml 节点中的错误更改值 [英] Error change values in node of a xml

查看:40
本文介绍了xml 节点中的错误更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

这是代码:

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

问候和感谢.

推荐答案

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

这看起来不对.desc 是一个属性,不是子属性,对吧?

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

应该是row2.getAttributeNode("desc").setValue("valor")

这篇关于xml 节点中的错误更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆