Daniel Paiva
Daniel Paiva

Reputation: 121

C# validating a XML with a XSD

I am new at C# and I am trying to create an .exe using C# and Visual Studio Code (VSC). The .exe shall receive two arguments that are the complete paths for the xsd and xml files.

Example:

I was adapting a code that I found, because this is not a new "problem" in IT or C#.

static void Main(string[] args) {
    if (args == null)
    {
        throw new ArgumentNullException ("source");
    } else {
    var xsdfile = "";
    var xmlfile = "";
    for (int i = 0; i < args.Length; i++){
        if (i==0){
            xsdfile = args[i];
        } else if (i==1){
            xmlfile = args[i];
        }
    }
    XmlSchemaSet schema = new XmlSchemaSet();
    if (xsdfile != null){
        schema.Add("", xsdfile);
    } 
    XmlReader rd = XmlReader.Create(xmlfile);  
    XDocument doc = XDocument.Load(rd);  
    doc.Validate(schema, ValidationEventHandler);  
    }  
    static void ValidationEventHandler(object sender, ValidationEventArgs e) {  
    XmlSeverityType type = XmlSeverityType.Warning;  
        if (Enum.TryParse < XmlSeverityType > ("Error", out type)) {  
        if (type == XmlSeverityType.Error) throw new Exception(e.Message);  
        }  
    }
}

When I am debbuging the code in VSC and it is being displayed the following error: Line 37: schema.Add("", xsdfile);

System.ArgumentNullException in System.Private.Xml.dll: 'Value cannot be null'.

Since I have to low experience with C#, I don't know how to fix this problem and if my code it is correctly to handle the urls.

Can anyone help me to try to resolve this problem?

Upvotes: 0

Views: 4104

Answers (1)

William Walseth
William Walseth

Reputation: 2923

This does what you're looking for, good luck.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

namespace xmlutil {
    class Program {
        static void Main(string[] args) {

            string strFileName = String.Empty;

            try {

                if (args.Length < 2) {
                    throw new Exception("Usage: xmlutil.exe [file.xml|folder\\*.xml] file.xsd");
                }

                System.IO.FileAttributes attr = System.IO.File.GetAttributes( args[0] );

                XmlReaderSettings settings = new XmlReaderSettings();

                strFileName = args[1]; // to detect errors in the schema

                settings.Schemas.Add(null, args[1]);
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationFlags =
                                XmlSchemaValidationFlags.ReportValidationWarnings |
                                XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                XmlSchemaValidationFlags.ProcessInlineSchema |
                                XmlSchemaValidationFlags.ProcessSchemaLocation;


                if (attr.HasFlag(System.IO.FileAttributes.Directory)) {

                    string[] directories = Directory.GetDirectories(args[0]);




                    string[] files = Directory.GetFiles(args[0], "*.xml", SearchOption.AllDirectories);
                    int i = files.Length;
                    Console.WriteLine("Processing folder " + args[0] + " - " + i + " files.");

                    int nTen = Convert.ToInt32(files.Length / 10);
                    int nCount = 0;

                    for (i = 0; i < files.Length; i++) {
                        strFileName = files[i];
                        try {
                            ValidateFile(files[i], settings);

                            if ((i % nTen) == 0) {
                                if (nCount > 0) {
                                    Console.WriteLine(nCount * 10 + "% complete.");
                                }
                                nCount++;
                            }
                        } catch (Exception ex2) {
                            Console.Error.WriteLine(strFileName);
                            Console.Error.WriteLine(ex2.Message);
                        }
                    }
                } else {
                    strFileName = args[0];
                    ValidateFile(args[0], settings);
                }
            } catch (XmlSchemaException exs) {
                Console.Error.WriteLine(strFileName + " schema validation exeption" );
                Console.Error.WriteLine(exs.Message + " Line: " + exs.LineNumber + " Column: " + exs.LinePosition );
            } catch (Exception ex) {
                Console.Error.WriteLine(strFileName);
                Console.Error.WriteLine(ex.Message);
            }
            
        }

        static void ValidateFile(string strXMLFile, XmlReaderSettings settings) {

            XmlDocument document = new XmlDocument();
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            XmlReader reader = XmlReader.Create(strXMLFile, settings);
            document.Load(reader);
            // the following call to Validate succeeds.
            document.Validate(eventHandler);
        }

        static void ValidationEventHandler(object sender, ValidationEventArgs e) {
            switch (e.Severity) {
                case XmlSeverityType.Error:
                    Console.WriteLine("Error: {0}", e.Message);
                    break;
                case XmlSeverityType.Warning:
                    Console.WriteLine("Warning {0}", e.Message);
                    break;
            }

        }
    }
}

Upvotes: 3

Related Questions