I am trying to access some values in an XML document with Dom parser and I am getting a strange null pointer exception error. the code I am using is:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class readXML {
public static void main(String[] args) {
File file = new File("C:\\Users\\manolaki\\Desktop\\assets.xml");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
doc.getDocumentElement().normalize();
Node node = doc.getElementsByTagName("assets").item(0).getChildNodes().item(1).getChildNodes().item(1).getAttributes().getNamedItem("src");
String boo = node.getNodeValue();
System.out.println("Name is " + boo);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
the xml I am Using:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<assets>
<sprite>
<img src="menu.png"/>
</sprite>
<sprite>
<img src="background.png"/>
</sprite>
<sprite>
<img src="buttons.png"/>
</sprite>
<sprite>
<img src="animals.png"/>
</sprite>
<sprite>
<img src="cycles.png"/>
</sprite>
<sprite>
<img src="texts.mp3"/>
</sprite>
<sprite>
<img src="music.mp3"/>
</sprite>
<sprite>
<img src="click.mp3"/>
</sprite>
<sprite>
<img src="swipe.mp3"/>
</sprite>
<sprite>
<img src="dog.mp3"/>
</sprite>
</assets>
<assets>
<sprite>
<img src="mehnu.png"/>
</sprite>
<sprite>
<img src="background.png"/>
</sprite>
<sprite>
<img src="buttons.png"/>
</sprite>
<sprite>
<img src="animals.png"/>
</sprite>
<sprite>
<img src="cycles.png"/>
</sprite>
<sprite>
<img src="texts.mp3"/>
</sprite>
<sprite>
<img src="music.mp3"/>
</sprite>
<sprite>
<img src="click.mp3"/>
</sprite>
<sprite>
<img src="swipe.mp3"/>
</sprite>
<sprite>
<img src="dog.mp3"/>
</sprite>
</assets>
</xml>
The code works fine as is and it prints out "menu.png" at the console. The problem is that while I can navigate through the assets nodes using the first "Item()" part, if i try to change the second "item()" to navigate through the sprites it prints a null pointer exception error. for example it works if I use:
Node node = doc.getElementsByTagName("assets").item(1).getChildNodes().item(1).getChildNodes().item(1).getAttributes().getNamedItem("src");
but not when I use
Node node = doc.getElementsByTagName("assets").item(0).getChildNodes().item(2).getChildNodes().item(1).getAttributes().getNamedItem("src");
Which I think is kind of strange.. given that eclipse is not finding any errors. any help would be appreciated. thanks