stackoverflow
stackoverflow

Reputation: 19484

Java Using Saxparser results in exception thrown

CODE:

public void parse(byte[] payload)
{
    try
    {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler()
        {
            boolean eid = false;
            boolean msg_id = false;
            boolean date_time = false;
            boolean temp = false;

            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
            {
                if (qName.equalsIgnoreCase("eid"))
                {
                    eid = true;
                }

                if (qName.equalsIgnoreCase("msg_id"))
                {
                    msg_id = true;
                }

                if (qName.equalsIgnoreCase("date_time"))
                {
                    date_time = true;
                }

                if (qName.equalsIgnoreCase("temperature"))
                {
                    temp = true;
                }
            }

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

                if (eid)
                {
                    XMLMessagePacket.this.eid = new String(ch, start, length);
                    eid = false;
                }

                if (msg_id)
                {
                    XMLMessagePacket.this.msgId = new String(ch, start, length);
                    msg_id = false;
                }

                if (date_time)
                {
                    XMLMessagePacket.this.time =  new String(ch, start, length);
                    date_time = false;
                }

                if (temp)
                {
                    XMLMessagePacket.this.temperature.parseDouble(new String(ch, start, length));
                    temp = false;
                }

            }

        };

        saxParser.parse(new ByteArrayInputStream(payload), handler);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

XML

<?xml version="1.0"?>
<event>
        <eid>345345</eid>
        <msg_id>3242</msg_id>
        <date_time>11342345</date_time>
        <temperature>100</temperature>
</event>

Problem:

org.xml.sax.SAXParseException: Content is not allowed in prolog.

Upvotes: 1

Views: 1056

Answers (1)

hcayless
hcayless

Reputation: 1046

Just something to check: a friend once fought this "bug" all night. Is it possible your file has a Byte Order Mark at the beginning? Parsing it as a String might make it disappear. The default encoding for XML is UTF-8 (which does not require a BOM). It's just possible you're getting tripped up by something you can't see.

Upvotes: 1

Related Questions