在没有try/catch的情况下检查格式良好的XML?

Ste*_*per 26 c# xml well-formed

有没有人知道如何XmlDocument.LoadXml()在不使用try/catch块之类的东西的情况下检查字符串是否包含格式良好的XML ?我有输入可能是也可能不是XML,我希望代码能够识别输入可能不是XML而不依赖于try/catch,速度和非特殊情况不应该提高的一般原则例外.我目前有代码执行此操作;

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它似乎不应该需要try/catch.异常是在调试期间导致快乐的地狱,因为每次我检查字符串时调试器都会在这里打破,"帮助"我解决我的麻烦问题.

Jon*_*eet 24

我不知道一种没有例外的验证方法,但你可以将调试器设置更改为仅XmlException在未处理的情况下中断- 这应该可以解决您的直接问题,即使代码仍然不优雅.

为此,请转到Debug/Exceptions .../Common Language Runtime Exceptions并找到System.Xml.XmlException,然后确保仅选中"User-unhandled"(不是Thrown).


Gre*_*zer 8

史蒂夫,

我们有一个第三方偶然发送了JSON而不是XML.这是我实施的:

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));
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*hen 6

这是一种合理的方法,除了IsNullOrEmpty是冗余的(LoadXml可以很好地解决这个问题).如果确实保留了IsNullOrEmpty,请执行if(!string.IsNullOrEmpty(value)).

但基本上,您的调试器是问题,而不是代码.