java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

<submission>
	<submissionMetadata submitedOn="Mon Oct 14 11:33:57 EDT 2013" submitedByName="My Name" submitedByUsername="hanli" ermProcessId="132385" instanceId="126528"/>
	<submissionModel>
		<dataValue fieldName="version" value="1"/>
	</submissionModel>
</submission>

However, after I copy this into IDE and use:
Element metadataElement = (Element) rootNode.getFirstChild();

I am getting:
java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

It turns out :
The first child is the whitespace between the end of submission and the start of submissionMetadata.

Using w3c DOM to walk the tree is not so easy. If you don’t have to use w3c, I recommend dom4j – it is much nicer to use. For example, it will filter text nodes from elements, so you can call

List children = submission.elements();

or, to restrict by name

List children = submission.elements(“submissionMetadata”);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s