473,699 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XmlException and the XmlDocument class

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
XmlRootElementM issingException 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
XmlRootElementM issingException 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.
Aug 29 '08 #1
3 3531
On Aug 30, 12:21*am, Ed Kramer <EdKra...@discu ssions.microsof t.com>
wrote:
Looking over the XmlException object, I noticed it had a HRESULT propertyon
it in my watch window. That's great! I thought. I can uniquely identify this
exception and handle that case.
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.
Aug 31 '08 #2
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.Sourc e which just
says "System.Xml " and isn't very helpful.
"Pavel Minaev" wrote:
On Aug 30, 12:21 am, Ed Kramer <EdKra...@discu ssions.microsof t.com>
wrote:
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.

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.
Sep 5 '08 #3
"Ed Kramer" <Ed******@discu ssions.microsof t.comwrote in message
news:72******** *************** ***********@mic rosoft.com...
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.Sourc e which
just
says "System.Xml " and isn't very helpful.
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.
Sep 6 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3606
by: KathyB | last post by:
If someone could just explain this to me...I just don't get it! I have an aspx page where I retrieve several session variables and use xmlDocument to transform xml file with xsl file into an instruction document (not data based) - same as using an xml web control. The resulting html is on the client? but what about the server side of things? Trying to figure out how to change and save the xmlDocument. It I put a button OUTSIDE of the...
3
22352
by: Todd | last post by:
Our ASP.NET (C#) application accepts form entry and saves inputed data in XML. We are finding that users are sometimes cutting and pasting special characters (from MS Word) into these forms. The data is saved successfuly, but when the XML is later read the following error is encountered depending on the invalid character found: This is a sample:
1
1847
by: edi | last post by:
Hi, I have MS .Net Framework v1.1.4322. I have this XML file: <?xml version="1.0" ?> <!--here there are two spaces at the beginning--> <aaa> <a id="1"> <Dept>Finance</Dept>
3
1863
by: Mungo Jerrie | last post by:
Hi there :-) I have some problems with the same instance of my xmldocument across 3 different classes. See code below: class one { protected static XmlDocument doc = new XmlDocument(); public static XmlDocument getXmlDocument(){
0
3338
by: Frederico Guimar?es via DotNetMonster.com | last post by:
Hi, I'm trying to use the Microsoft.Web.Services2.Messaging. ISoapFormatter but I receive this error: System.Xml.XmlException: The root element is missing. at System.Xml.XmlTextReader.Read() at Microsoft.Web.Services2.Xml.XmlSkipDTDReader.Read() at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
1
2334
by: mohit | last post by:
Hi, I am making a web application in Web Matrix on .NET framework. I have a Login.aspx File and a Users.xml file.I am reading data from Users.xml file using FileStream.The Code is DataSet ds = new DataSet ( ); FileStream fs = new FileStream ( Server.MapPath ( "Users.xml" ),
3
5993
by: RJA | last post by:
Hiyas, Using VS .net 2003. Setting up a Webservice that accepts 3rd party vendor designed XML requests and returns a filled XMLDocument with response data. Vendor XSDs were serialize into class objects to be used in the program. EX: Used xsd.exe to turn VendorA_Request.XSD into VendorA_Request.cs EX: Used xsd.exe to turn VendorA_Response.XSD into VendorA_Response.cs
2
13581
by: John Smith | last post by:
I'm writing webervice client using .Net 2.0. I have this class: public class MyWebService : SoapHttpClientProtocol { public XmlDocument validate(string url, XmlDocument xmlDocument) { this.Url = url;
1
2159
by: BLUE | last post by:
In a property i do this: .... catch(XmlException e) { throw new XmlException("Error processing configuration file!",e); } Then I catch it in another class: catch(XmlException e) {
0
8615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9174
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9034
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8914
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8883
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7750
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2347
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.