Why I get NullPointerException when running StAX Parser?

后端 未结 1 1742
不思量自难忘°
不思量自难忘° 2021-01-29 14:38

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

相关标签:
1条回答
  • 2021-01-29 15:21

    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 corresponding END_ELEMENT.

    Throws:
    XMLStreamException - if the current event is not a START_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());
    
    0 讨论(0)
提交回复
热议问题