You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用StaX解析XML遇到<p/>标签引发ClassCastException异常

Fixing java.lang.ClassCastException in XML Parsing with StAX

Let’s break down exactly why you’re hitting this error and how to fix it:

The exception com.sun.xml.internal.stream.events.EndElementEvent cannot be cast to javax.xml.stream.events.Characters means your parsing code is trying to treat an XML end element (like </p> or the closing part of a self-closing <p/>) as text content. This happens when your logic assumes every <p> start tag is immediately followed by text, but encounters an empty (self-closing) <p/> tag where there’s no text to read.

How to Fix the Parsing Logic

When using StAX (Streaming API for XML), you need to explicitly check the type of each event before casting or processing it. Here’s a corrected approach to safely parse your <p> elements:

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;

public class XmlParser {
    public static void main(String[] args) throws Exception {
        String xml = "<body xmlns=\"http://www.w3.org/1999/xhtml\"> <p>GENE_ASSOCIATION: BLA BLA</p> <p>BLA BLA: Purine metabolism</p> <p>BLA BLA: 2.7.4.3</p> <p>BLA BLA Level: 1</p> <p>AUTHORS:PMID:6182143;PMID:624...</p> <p/> </body>";
        
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(xml));
        
        while (reader.hasNext()) {
            int eventType = reader.next();
            
            switch (eventType) {
                case XMLStreamConstants.START_ELEMENT:
                    if ("p".equals(reader.getLocalName())) {
                        StringBuilder content = new StringBuilder();
                        // Iterate until we hit the closing </p> tag
                        while (reader.hasNext()) {
                            int innerEventType = reader.next();
                            if (innerEventType == XMLStreamConstants.CHARACTERS) {
                                content.append(reader.getText());
                            } else if (innerEventType == XMLStreamConstants.END_ELEMENT) {
                                // We've reached the end of the <p> element
                                System.out.println("P content: " + content.toString().trim());
                                break;
                            }
                            // Add handling for other event types (like CDATA) if needed
                        }
                    }
                    break;
            }
        }
        reader.close();
    }
}

Key Changes to Avoid the Exception:

  • Check Event Types: Never assume the next event is text content—always verify it’s of type XMLStreamConstants.CHARACTERS before accessing text.
  • Handle Empty Elements: The loop will gracefully exit when it hits the END_ELEMENT event, even for empty <p/> tags, avoiding invalid casts.
  • Trim Whitespace: Using trim() ensures you don’t get empty strings from whitespace between tags.

Quick Note for Event-Based Parsers

If you’re using XMLEventReader instead of XMLStreamReader, the same logic applies: check if the event is an instance of Characters before casting it.

内容的提问来源于stack exchange,提问作者ErEcTuS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:39:22