CSharp/C# >> XmlException and the XmlDocument class

by RWQgS3JhbWVy » Sat, 30 Aug 2008 04:21:01 GMT

I thought this might be useful for someone...

I was doing a little work earlier using an Xmldocument class to create &
maintain a minor store of data in Xml format.

I'd gotten the whole thing up and going and I decided to start testing
'disaster' scenarios.

For example, you start up but your file has been deleted, or you try to save
and the file is read only. Or you lack write permissions. Or you try to load
and the document is empty. Or the XML inside the document is malformed
because someone edited it manually.

I noticed that on the call to the XmlDocument's .Load(<stream>) method if
the document was empty it would throw an XmlException.

Unfortunately unlike much of the structured exception handling in .Net
that's a generic exception for a lot of different types of events. Other than
the LineNumber , LinePosition and Message properties, you're not really
getting much information there to uniquely identify specific Xml based
exceptions. In my case, I was getting an XmlException with a message of "Root
element is missing.". Yeah that tells me as the developer, but how do I
handle it other than catching XmlException. Catching generic exceptions is
bad practice.

In my case, if document.Load( ) failed that was ok. Because later in that
same method I'm actually setting up the document properly anyway before I
call .Save(). But, if I put a try/catch around .Load( ) and catch
XmlException, I would be catching everything related to XML coming out of
that call. Whether it be the root element missing or someone forgot a '>' on
line 182 column 12. I'd want to catch the former and allow the latter to go
right on by. Don't want to swallow all exceptions, after all. You can't try
to determine the type of exception based on the message, because that message
could be language dependent. What if I run it on a Cyrillic machine. Trying
to match "Root element is missing" in English against say Spanish isn't going
to match.

Looking over the XmlException object, I noticed it had a HRESULT property on
it in my watch window. That's great! I thought. I can uniquely identify this
exception and handle that case. Unfortunately the HResult property is a
protected member of the class. So, I couldn't grab hold if it directly to
even put it in a Switch to do something slightly more structured.

I also tried to use reflection to get that property's value, but that didn't
work well.

Then it occurred to me. It's a Protected method. So all I need to do is
derive a class from XmlException and that will give me access to the
property. I can then use that to identify the specific exception.

I then created a NeoXmlException class as a new base and created a
XmlRootElementMissingException that derived from it. I put a try/catch around
my call to document.Load( ), catching the generic XmlException. I then pass
that exception to an intermediary factory style class which if it wraps a
NeoXmlException around it, giving access to the protected HRESULT property.
If the factory can identify the type of specific XML exception it wraps one
of those specific classes around it and throws it. It it can't, it just
rethrows the original exception. As it stands right now I only have the
XmlRootElementMissingException class and everything else goes through like a
18-wheeler through a sedan. But as I find more errors that need this
treatment it's easy enough to add another class inheriting from XmlException
and add it to the factory.

I don't really understand why MS didn't either make separate exceptions in
the first place or give public access to HRESULT so we can do it ourselves.
Almost everything throws very specific exceptions which you can catch and
most books I've read say that catching generic exceptions ( the Exception
base class for example ) are very bad practice.

I just thought I'd post it here since it seems like a useful (if convoluted)
solution to this problem. Of course if anyone has a better idea lemme know so
I can revise my XML IO classes.

CSharp/C# >> XmlException and the XmlDocument class

by Pavel Minaev » Sun, 31 Aug 2008 16:32:47 GMT


On Aug 30, 12:21燼m, Ed Kramer < XXXX@XXXXX.COM >


Have you actually checked whether HRESULT is unique for the specific
exception you're trying to catch?

By the way, you should also check InnerException. Quite often, that's
where the actual cause of the problem is - and you can check its type
to see what it was.

CSharp/C# >> XmlException and the XmlDocument class

by RWQgS3JhbWVy » Sat, 06 Sep 2008 00:00:27 GMT

With more testing it seems that same HRESULT comes up for different problems
and not just the one I noted above. Which is basically throwing a
monkeywrench into things.

as far as inner exception, it's showing up as 'null' in the debug window as
is the property 'helplink' and the Values collection on the Data property
dictionary is empty. The only properties I really see with anything in them
are the message property, the stacktrace and the exception.Source which just
says "System.Xml" and isn't very helpful.

CSharp/C# >> XmlException and the XmlDocument class

by Pavel Minaev » Sat, 06 Sep 2008 15:43:24 GMT


Usually, exceptions thrown by XmlDocument have a pretty detailed error
message explaining the cause of the problem (with line number in the XML) in
its Message property. If XML input comes from the user, you can just display
that to him. If you want localization, you can deploy .NET Framework
language packs on the end user machines - it'll localize the exception
messages, too.

If you're just trying to do some quiet internal recovery, then perhaps it is
better to use something like XmlReader. Since it reads input XML
token-by-token, it will only throw the exception once you get to the point
in input XML that is faulty, and you can keep track of the state to know
precisely where and what it is.

Similar Threads

1. Curious: Why use XPathNavigator Class over XMLDocument Class?

Any opinions on the best way to load, select nodes (anywhere in the
tree), manipulate those nodes, and save the changes?  Any reason I
should change from just straight up manipulating the XMLDocument and
use the XPathNavigator class?  Is the performance is better then using
the XMLDocument class to perform XPath queries?  What is the most
efficient method of manipulating and saving data changes?

Cheers,

-- Curious.

2. adding elements of XmlDocument A in XmlDocument B - CSharp/C#

3. Get all namespace prefix from XmlDocument class

Hi,

if I have xml document
<root xmlns:a="myNS1" xmlns:b="myNS2" xmlns="myNS">
  <a:node1>value1</a:node1>
  <b:node2>value2</b:node2>
  <node3>value3</node3>
</root>

if I load the above xml in XmlDocument, I can get the namespaceURI "myNS1" 
usnig .GetNamespaceOfPrefix("a")

Could someone tell me how to get/enumerate all namespace prefixes and 
namespaceURIs?

Thanks very much!
John 


4. How to transform a custom class into xmlDocument object - VB.Net

5. Slowness of XmlDocument Class

I'm working with the compact framework and trying to write a program that
will roll through a xml document and display the information in a listbox,
but after I open a file with a OpenFileDialog it takes up to 15 seconds to
load the file into the XmlDocument.  Any Ideas on how to speed the code up.
My xml file is around 200k.  Here is a sample of the code that i'm using.

lstCaches.Items.Clear();

OpenFileDialog GetGPX = new OpenFileDialog();

GetGPX.Filter = "GPX files (*.GPX)|*.gpx|All files (*.*)|*.*";

GetGPX.ShowDialog();

FileName = GetGPX.FileName;

if(FileName != "")

{

XmlDocument GpxDoc = new XmlDocument();



GpxDoc.Load(GetGPX.FileName);

}



Thanks,

Justin


6. Passing XmlDocument-derived class in a WebMethod

7. Load method of XmlDocument class fails for an invalid character

Hi,
The error you are getting is valid.An ampersand is a reserved character in 
XML and it signals the beginning of an entity (in this case, a special 
character)So, " & " is illegal in XML.Instead of "&" you need to use the 
entity reference for the ampersand: that is it should be &
other special characters in XML are: < for <; > for >; ' for '; and " 
for ".

so you need to make your  xml string valid before passing to LoadXML() 
function.(that is by replacing & with &) 

Hope this helps you out.

Thanks and Regards,
Manish Bafna.
MCP and MCTS.





"Roy" wrote:

> Hi all,
> There is a character in my xml file () that causes loading of an xml file 
> to a datatable to fail. In XML's header, I've changed the encoding property 
> from 8 to 16 (encoding="UTF-16"), but even this change didn't resolve the 
> issue. Is there anything else I need to do to resolve this loading issue? Or 
> Should I take another approach for loading xml (if there is one)?
> Thanks in advance,
> Roy
> 

8. Load operation of XMLDocument Class - .Net Framework