1

代码:

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>

问题:

org.xml.sax.SAXParseException:prolog 中不允许有内容。

4

1 回答 1

1

只是要检查一下:一位朋友曾经整晚都在与这个“错误”作斗争。您的文件是否可能在开头有一个字节顺序标记?将其解析为字符串可能会使其消失。XML 的默认编码是 UTF-8(不需要 BOM)。你有可能被你看不到的东西绊倒了。

于 2013-01-23T00:50:26.540 回答