我需要更改 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");
}
问候和感谢。
row2.getChild("desc").setText("valor");
这看起来是错误的。 desc 是一个属性,而不是子属性,对吗?
它应该是row2.getAttributeNode("desc").setValue("valor")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)