Check well-formed XML without a try/catch?

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.


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).


Steve,

We had an 3rd party that accidentally sometimes sent us JSON instead of XML. Here is what I implemented:

public static bool IsValidXml(string xmlString)
{
    Regex tagsWithData = new Regex("<\\w+>[^<]+</\\w+>");

    //Light checking
    if (string.IsNullOrEmpty(xmlString) || tagsWithData.IsMatch(xmlString) == false)
    {
        return false;
    }

    try
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlString);
        return true;
    }
    catch (Exception e1)
    {
        return false;
    }
}

[TestMethod()]
public void TestValidXml()
{
    string xml = "<result>true</result>";
    Assert.IsTrue(Utility.IsValidXml(xml));
}

[TestMethod()]
public void TestIsNotValidXml()
{
    string json = "{ \"result\": \"true\" }";
    Assert.IsFalse(Utility.IsValidXml(json));
}