使用XmlStreamReader跳过无效的xml元素

时间:2016-03-12 06:56:23

标签: java xml xml-parsing xmlstreamreader

我想解析我的xml:

<?xml version="1.0" encoding="UTF-8" ?>
<REPLY SERVICENAME="ServerWrapper">
    <ROWSET name="ServiceName">
        <ROW num="1">
            <AMOUNT_TOTAL>26865</AMOUNT_TOTAL>
            <REQUESTED_SEARCH_VALUE>eur</REQUESTED_SEARCH_VALUE>
            <SELECTED_ID>ABC,XYZ</SELECTED_ID>
            <AMOUNT>10</AMOUNT>
            <ABC,XYZ.AMOUNT>26865</ABC,XYZ.AMOUNT>
            <ROWSET name="ServiceName.DATA">
                <ROW num="1">
                </ROW>
                ...
             </ROWSET>
        </ROW>
    </ROWSET>
</REPLY>

在这个XML中,我需要跳过无效元素<ABC,XYZ.AMOUNT>26865</ABC,XYZ.AMOUNT>。我正在使用XMLStreamReader类来解析xml。

我的解析器类:

public Object decode(String xml) {
    XMLInputFactory xmlFactory = null;
    String textValue = "";
    xmlFactory = XMLInputFactory.newInstance();
    try {
        xmlFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);

        XMLStreamReader xmlReader;
        InputStream stream = new ByteArrayInputStream(xml.getBytes());

        xmlReader = xmlFactory.createXMLStreamReader(stream);

        while (xmlReader.hasNext()) {
            int eventType;
            try {
                eventType = xmlReader.next();
            } catch (XMLStreamException ex) {
                continue;
            }

            switch (eventType) {
                case XMLEvent.START_ELEMENT:
                    treePath.append("/").append(xmlReader.getLocalName());
                    attribute(xmlReader);
                    break;
                case XMLEvent.END_ELEMENT:
                    endElement(xmlReader, textValue);
                    break;
                case XMLEvent.END_DOCUMENT:
                    endDocument();
                    break;
                case XMLEvent.CHARACTERS:
                    textValue = xmlReader.getText();
                    break;
                default:
                    break;
            }
        }

    } catch (XMLStreamException ex) {
        LOGGER.error("Error on parsing data", ex);
        ex.printStackTrace();
    }

    LOGGER.info("Decode finished on[{}]", Calendar.getInstance().getTime());

    Object[] response = new Object[1];        
    response[0] = responseList;
    return response;
}

但是在解析时我得到了一个异常:

javax.xml.stream.XMLStreamException: ParseError at [row,col]:[2,237]
Message: Element type "ABC" must be followed by either attribute specifications, ">" or "/>".
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:601)

有人可以帮我解决这个问题吗?

0 个答案:

没有答案