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

后端 未结 7 1835
挽巷
挽巷 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 15:00

    If you have an XSD for the XML, try this:

    using System;
    using System.Xml;
    using System.Xml.Schema;
    using System.IO;
    public class ValidXSD 
    {
        public static void Main()
        {
            // Set the validation settings.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    
            // Create the XmlReader object.
            XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
    
            // Parse the file. 
            while (reader.Read());
        }
    
        // Display any warnings or errors.
        private static void ValidationCallBack (object sender, ValidationEventArgs args) 
        {
            if (args.Severity == XmlSeverityType.Warning)
                Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
            else
                Console.WriteLine("\tValidation error: " + args.Message);
        }  
    }
    

    Reference is here:

    http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.validationeventhandler.aspx

    0 讨论(0)
提交回复
热议问题