I\'m trying to write a StAX XML Parser in Java, but always get NullPointerException error. Please help me to solve this issue. Full problem:
Exception in thr
UPDATED: Comment to original answer:
It doesn't work, it gives the same error
That means the problem is because the shoes
variable is null
, as would have easily been seen with a debugger. Using a debugger would have saved us all a lot of time, so please start using one.
In order for shoes
to be null
, it appears that the code encountered a <title>
element that is not a child of a Shoes
element.
To fix the code, add a null-check, and also set shoes = null
at the end of processing the Shoes
element:
} else if (startElement.getName().getLocalPart().equals("title")) {
if (shoes != null) { // <===== ADD THIS
shoes.setTitle(reader.getElementText()); // <===== Fix this (see original answer)
}
if (xmlEvent.isEndElement()) {
EndElement endElement = xmlEvent.asEndElement();
if (endElement.getName().getLocalPart().equals("Shoes")) {
shoesList.add(shoes);
shoes = null; // <===== ADD THIS
}
}
ORIGINAL ANSWER
Your code is:
} else if (startElement.getName().getLocalPart().equals("title")){
xmlEvent = reader.nextEvent();
shoes.setTitle(xmlEvent.asCharacters().getData());
The problem is that the code isn't checking what type if event follows the START_ELEMENT
event. It could be that:
Most likely, the element is empty, i.e. <title/>
or <title><title/>
, in which case the next event is an END_ELEMENT
, and asCharacters()
returned null
.
The element has a comment, e.g. <title><!-- there is no title --><title/>
, in which case the next event is a COMMENT
.
The element has mixed content, e.g. <title>foo<![CDATA[bar]]><title/>
, in which case the next event is not the full text.
Retrieving the text content of an element is such a common thing that they added a helper method for that: getElementText():
Reads the content of a text-only element. Precondition: the current event is
START_ELEMENT
. Postcondition: The current event is the correspondingEND_ELEMENT
.Throws:
XMLStreamException
- if the current event is not aSTART_ELEMENT
or if a non text element is encountered
Which means that your code should be:
} else if (startElement.getName().getLocalPart().equals("title")) {
shoes.setTitle(reader.getElementText());