How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?

后端 未结 7 1833
挽巷
挽巷 2020-12-28 14:24

I\'m loading an XML document in my C# application with the following:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);

but be

7条回答
  •  生来不讨喜
    2020-12-28 14:40

    As has previously been mentioned "valid xml" is tested by XmlDocument.Load(). Just catch the exception. If you need further validation to test that it's valid against a schema, then this does what you're after:

    using System.Xml; 
    using System.Xml.Schema; 
    using System.IO; 
    
    static class Program
    {     
        private static bool _Valid = true; //Until we find otherwise 
    
        private static void Invalidated() 
        { 
            _Valid = false; 
        } 
    
        private static bool Validated(XmlTextReader Xml, XmlTextReader Xsd) 
        { 
    
            var MySchema = XmlSchema.Read(Xsd, new ValidationEventHandler(Invalidated)); 
    
            var MySettings = new XmlReaderSettings(); 
            { 
                MySettings.IgnoreComments = true; 
                MySettings.IgnoreProcessingInstructions = true; 
                MySettings.IgnoreWhitespace = true; 
            } 
    
            var MyXml = XmlReader.Create(Xml, MySettings); 
            while (MyXml.Read) { 
              //Parsing...
            } 
            return _Valid; 
        } 
    
        public static void Main() 
        { 
            var XsdPath = "C:\\Path\\To\\MySchemaDocument.xsd"; 
            var XmlPath = "C:\\Path\\To\\MyXmlDocument.xml"; 
    
            var XsdDoc = new XmlTextReader(XsdPath); 
            var XmlDoc = new XmlTextReader(XmlPath); 
    
            var WellFormed = true; 
    
            XmlDocument xDoc = new XmlDocument(); 
            try { 
                xDoc.Load(XmlDoc); 
            } 
            catch (XmlException Ex) { 
                WellFormed = false; 
            } 
    
            if (WellFormed & Validated(XmlDoc, XsdDoc)) { 
              //Do stuff with my well formed and validated XmlDocument instance... 
            } 
        } 
    } 
    

提交回复
热议问题