Parsing an xml response from a url using STAX

2019-07-27 03:53发布

问题:

I am sending a xml request through java code and getting the xml response using the below code:

BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = rd.readLine()) != null) {
        sb.append(line + '\n');
    }

Now I need to parse the xml response using STAX so I have written a method for parsing:

XMLReader reader = new XMLReader();
ArrayList<String> List = reader.parse(connection.getInputStream());

and in the parse() I have reader = factory.createXMLEventReader(connection.getInputStream());

However I am getting the following error:

javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Premature end of file.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:593)
at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(XMLEventReaderImpl.java:85)

Can someone please advise me where I am going wrong here?

Thanks,

swati

回答1:

Sorry the question is similar to this one : Error while parsing XML file with StAx.

Since before parsing, I was reading the content, the parsing was failing. As once you read the input stream, the stream closes and for parsing there was nothing to read.

Yes Ed, I was trying to read the same response twice.



标签: java xml url stax