How to check for valid xml in string input before calling .LoadXml()

后端 未结 5 516
一个人的身影
一个人的身影 2020-11-30 05:48

I would much prefer to do this without catching an exception in LoadXml() and using this results as part of my logic. Any ideas for a solution that doesn\'t in

5条回答
  •  青春惊慌失措
    2020-11-30 06:10

    I was unable to get XmlValidatingReader & ValidationEventHandler to work. The XmlException is still thrown for incorrectly formed xml. I verified this by viewing the methods with reflector.

    I indeed need to validate 100s of short XHTML fragments per second.

    public static bool IsValidXhtml(this string text)
    {
       bool errored = false;
       var reader = new XmlValidatingReader(text, XmlNodeType.Element, new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None));
       reader.ValidationEventHandler += ((sender, e) => { errored = e.Severity == System.Xml.Schema.XmlSeverityType.Error; });
    
       while (reader.Read()) { ; }
       reader.Close();
       return !errored;
    }
    

    XmlParserContext did not work either.

    Anyone succeed with a regex?

提交回复
热议问题