Posted in General

Invalid Cast Exception XMLElement

You wrote a class say StoredItemElement, that inherited from XmlElement class. When you open the document and try to cast the Element to StoredItemElement, you get an exception “Cannot cast ‘this.SelectSingleNode(“/WorkFlow/Messages”)’ (which has an actual type of ‘System.Xml.XmlElement’) to ‘Roadhouse.WorkFlow.Engine.Messages'”. In other words its “Specified cast is not valid” exception. Then do the following…

1. Don’t use XmlDocument, write a class, say StoredElementDocument : XmlDocument
2. Override the CreateElement method in StoredElementDocument as below..

public override XmlElement CreateElement( string prefix, string localname, string namespaceuri )
{
switch(localname)
{

case “StoredItemElement”:
return new StoredItemElement(prefix, localname, namespaceuri, this);
// ….. Any other XmlElements
default:
return base.CreateElement(prefix, localname, namespaceuri);
}
}

3. Use StoredElementDocument instead of XmlDocument
StoredElementDocument doc = new StoredElementDocument();
doc.Load("File.xml");
StoredItemElement element =
(StoredItemElement)doc.SelectSingleNode("//StoredItem");

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