Groups | Blog | Home
all groups > dotnet xml > september 2004 >

dotnet xml : Problem with inheriting from XmlElement class


Compic
9/12/2004 4:34:07 PM
Hi!
I have this class:
public class StoredItemElement : XmlElement

{

protected internal StoredItemElement(string prefix, string localName, string
namespaceUri, XmlDocument doc) : base(prefix, localName, namespaceUri, doc)
{ }

....

}

which inherits from XmlElement.

But when I try this:

XmlDocument doc = new XmlDocument();

doc.Load("File.xml");

StoredItemElement element =
(StoredItemElement)doc.SelectSingleNode("//item");

I get InvalidCastException, but I don't know where the problem is.

Can you help me?

Thanks in advance.

Martin Honnen
9/12/2004 6:20:04 PM


[quoted text, click to view]


[quoted text, click to view]

You can't cast an instance of the class XmlElement to an instance of
your derived class StoredItemElement, try
doc.SelectSingleNode("//item").getType()
and you will find that it shows
System.Xml.XmlElement
and you can't simply cast that to your StoredItemElement.
You would need to overwrite the SelectSingleNode method to return a
StoredItemElement instance when possible if you want to be able to cast
its result to that type.

That is simply how casting works in C#/.NET I think, nothing you could
change about that.

--

Martin Honnen
Oleg Tkachenko [MVP]
9/12/2004 7:46:20 PM
[quoted text, click to view]

That's wrong. You should also extend XmlDocument and override
CreateElement method. See
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconextendingdom.asp

--
Oleg Tkachenko [XML MVP]
AddThis Social Bookmark Button