Parse XML by ID in Java



I'm trying to parse a XML-File by ID. But I always get a NullPointerExeption.


My XML looks like this:



<root>
<default>
<area>
<param id="hello">Hello</param>
<param id="hey">Hey</param>
</area>
</default>
</root>


My Java code:



try {
String text;
File xmlFile= new File("C:\\Users\\Public\\Desktop\\test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);

text = doc.getElementById("hello").getTextContent(); // NullPointer
System.out.println(text);
} catch (Exception e){
e.printStackTrace();
}


I get the NullPointer at this line:



text = doc.getElementById("hello").getTextContent();


I debuged it. The Object doc isn't null. So I think it can't find the id "hello".


Thanks for helping!


No comments:

Post a Comment