views:

1591

answers:

4

Does anyone know how I can check if a string contains well-formed XML without using something like XmlDocument.LoadXml() in a try/catch block? I currently have code that does this;

private bool IsValidXML(string value)
    {
        try
        {
   // Check we actually have a value
   if (string.IsNullOrEmpty(value) == false)
   {
    // Try to load the value into a document
    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.LoadXml(value);

    // If we managed with no exception then this is valid XML!
    return true;
   }
   else
   {
    // A blank value is not valid xml
    return false;
   }
        }
        catch (System.Xml.XmlException)
        {
            return false;
        }
    }

But it seems like something that shouldn't require the try/catch. The exception is causing merry hell during debugging because every time I check a string the debugger will break here, 'helping' me with my pesky problem.

+7  A: 

I don't know a way of validating without the exception, but you can change the debugger settings to only break for XmlException if it's unhandled - that should solve your immediate issues, even if the code is still inelegant.

To do this, go to Debug / Exceptions... / Common Language Runtime Exceptions and find System.Xml.XmlException, then make sure only "User-unhandled" is ticked (not Thrown).

Jon Skeet
+1 for this life-saving solution. I only enable breaking on handled exception if I have to debug the failing code.
OregonGhost
+3  A: 

That's a reasonable way to do it, except that the IsNullOrEmpty is redundant (LoadXml can figure that out fine). If you do keep IsNullOrEmpty, do if(!string.IsNullOrEmpty(value)).

Basically, though, your debugger is the problem, not the code.

Matthew Flaschen
I've come to agree. I've marked up the method with a debugger attribute [DebuggerStepThrough] which stops the debugger stopping on the exception.
Steve Cooper
The IsNullOrEmpty is just an optimization to avoid the overhead of an exception when you call IsValidXml("") -- which happens a great deal in my program.
Steve Cooper
+1  A: 

I tried with the following objects, unsuccessfully:

  • XmlReader
  • XmlTextReader
  • XmlValidatingReader

A quick inspection using reflector show there is no way out of the throw block.

I searched for a regex to do it but could not find one. Does anyone know of one?

Dan
Hi, Dan. There's no regex that could validate XML, because XML isn't a Regular Language. So you need a full-bodied parser to do the job.
Steve Cooper
A: 

Add the [System.Diagnostics.DebuggerStepThrough] attribute to the IsValidXml method. This suppresses the XmlException from being caught by the debugger, which means you can turn on the catching of first-change exceptions and this particular method will not be debugged.

Steve Cooper