C# 用 XSD 验证 XML

C# validating a XML with a XSD

我是 C# 的新手,我正在尝试使用 C# 和 Visual Studio 代码 (VSC) 创建一个 .exe。 .exe 应接收两个参数,它们是 xsd 和 xml 文件的完整路径。

示例:

我正在改编我找到的代码,因为这不是 IT 或 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);  
        }  
    }
}

当我在 VSC 中调试代码时,它显示以下错误: 第 37 行:schema.Add("", xsdfile);

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

由于我对 C# 的经验不足,我不知道如何解决这个问题以及我的代码是否可以正确处理 url。

谁能帮我解决这个问题?

这就是您想要的,祝您好运。

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;
            }

        }
    }
}