检测解析xml文件的特定异常

时间:2014-02-12 10:10:49

标签: c# xml

我正在尝试检测xml文件中的特定异常,例如

  1. “第1行第45位的'childone'开始标记与'node'的结束标记不匹配。第1行,第82位。”

  2. “解析EntityName时出错。第1行,第45位。”

  3. 说我的xml字符串是

    <root><node some=\"fggfg\"><childone>name is &&</childone><childtwo>name9</childtwo></node>\n</root>
    

    其中存在特殊字符,即&amp;和LoadXml方法抛出异常号。 2,对于丢失的节点,它抛出异常号。 1。

    if (!isXmlParse(inputXml, out exceptionMsg))
    {
       bool done = XmlEscaper (inputXml, out escapeXml);
    }
    

    我的期望是isXmlParse方法仅在xml值包含特殊字符(如上面的示例xml)时返回false,并且即使对于缺少的节点或任何其他错误也返回true,并将异常消息返回到out参数。请帮我解决一下。

1 个答案:

答案 0 :(得分:0)

首先警告:我强烈建议您将XML修复到生成它的位置。不要使用字符串连接来生成XML。告诉任何创建XML的人他正在做一些非常错误的事情。使用XmlDocument或其他专用XML处理类会自动将&转换为&amp;并生成有效的XML。

除此之外,您可以完全按照文本形式的要求实施。

  • 抓住例外
  • 检查错误消息
  • 根据结果,返回true或false

    private static bool isXmlParse(string inputXml, out string exceptionMsg)
    {
        // TODO: Career warning - implementing workarounds instead of real fixes may harm your career.
        try
        {
            var d = new XmlDocument();
            d.LoadXml(inputXml);
            exceptionMsg = null;
        }
        catch (XmlException ex)
        {
            exceptionMsg = ex.Message;
            if (ex.Message.StartsWith("An error occurred while parsing EntityName"))
                return true;
        }
        return false;
    }
    

警告编号2:方法XmlEscaper()不易实现除非您确定&的所有出现都无效,否则不能简单地将&amp;替换为& 。如果XML看起来像

...<childdone>name is &amp;&</childdone>...

您只能替换第二个&字符。我肯定会把这部分留给你。