GayashanNA
GayashanNA

Reputation: 478

org.apache.axiom.om.impl.llom.OMTextImpl cannot be cast to org.apache.axiom.om.OMElement

I'm trying to do the following.

OMElement soapEnvelope = new StAXOMBuilder(soapEnvelopXMLFilePath).getDocumentElement();
OMElement firstElement = soapEnvelope.getFirstElement().getFirstElement();

Then i iterate through the child elements of the firstElement like this.

Iterator<OMElement> items = firstElement.getChildren();
while (items.hasNext()) {
    OMElement element = items.next();
    // ....do some processing here...
}

But when i try to execute this following class cast exception occurs.

java.lang.ClassCastException: org.apache.axiom.om.impl.llom.OMTextImpl cannot be cast to org.apache.axiom.om.OMElement 

The error occurs when items.next() is assigned to element OMElement object.

Any idea why i'm getting this exception? I can't figure out any mismatch.

These are the contents of my sample xml file.

    <?xml version="1.0" encoding="utf-8"?>
    <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
        <soapenv:Body>
            <ns:MONITOR xmlns:ns="http://try.example.com">
                <ns:HOSTS>
                    <ns:HOST NAME="node1">
                        <ns:METRIC NAME="metric1" VALUE="1123"/>
                        <ns:METRIC NAME="metric3" VALUE="456"/>
                        <ns:METRIC NAME="metric2" VALUE="789"/>
                    </ns:HOST>
                    <ns:HOST NAME="node2">
                        <ns:METRIC NAME="metric1" VALUE="147"/>
                        <ns:METRIC NAME="metric3" VALUE="258"/>
                        <ns:METRIC NAME="metric2" VALUE="369"/>
                    </ns:HOST>
                </ns:HOSTS>
                <ns:HOSTS>
                    <ns:HOST NAME="node3">
                        <ns:METRIC NAME="metric1" VALUE="236"/>
                        <ns:METRIC NAME="metric3" VALUE="159"/>
                        <ns:METRIC NAME="metric2" VALUE="478"/>
                    </ns:HOST>
                </ns:HOSTS>
            </ns:MONITOR>
        </soapenv:Body>

Thanks.

Upvotes: 1

Views: 5444

Answers (2)

Andreas Veithen
Andreas Veithen

Reputation: 9154

Use getChildElements instead of getChildren.

Upvotes: 5

Sami Korhonen
Sami Korhonen

Reputation: 1303

Not every node is an element. You should cast children to OMNode and check, if they are elements, Whitespaces count as text nodes

Upvotes: 2

Related Questions