Raúl Puro Raúl Puro - 1 year ago 110
Java Question

Error change values in node of a xml

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

This is the code:

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"))){
xmlOut.output(doc, new FileWriter("c:\\prueba3.xml"));

Greetings and thanks.

Answer Source


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

It should be row2.getAttributeNode("desc").setValue("valor")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download