Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I open this XML in SAXParser?

public static void parseit(String thexml){
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser;

    try {
        saxParser = factory.newSAXParser();
        DefaultHandler handler = new DefaultHandler() {
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            }
            public void endElement(String uri, String localName, String qName)throws SAXException {

            }           
            public void characters(char ch[], int start, int length) throws SAXException {

            }               
         };      
        saxParser.parse(thexml, handler);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("e", "e", e);
            e.printStackTrace();
        }catch (ParserConfigurationException e) {
            e.printStackTrace();    
        }
}

This is my code. (many thanks to these guys: Can someone help me with this JAVA SAXParser?)

The problem is, I'm always getting into the IOException e. The message is this:

java.io.IOException: Couldn't open....and then my XML file.

My XML file is this, and it's a String:

<?xml version="1.0" encoding="UTF-8"?>
<result>
    <person>
        <first_name>Mike</first_name>
    </person>
</result>

Why can't it read my XML String?

like image 461
TIMEX Avatar asked Dec 03 '22 13:12

TIMEX


2 Answers

The parse method you call expects an URI to the XML file to read.

What you might want to do instead is to create an InputSource from a StringReader like this:

InputSource source = new InputSource(new StringReader(thexml));
saxParser.parse(source, handler);
like image 101
Joachim Sauer Avatar answered Dec 20 '22 08:12

Joachim Sauer


SAXParser's parse method expects a file name or URI as first argument, not an XML file read into a string.

like image 36
Tim Jansen Avatar answered Dec 20 '22 08:12

Tim Jansen