Databases /HW_XML/Parsers/HW_XML_Parsers/15.XSDValidation/XSDValidation.cs

Language C# Lines 61
MD5 Hash be00620aa8d4bc5a49beefc94375a497
Repository https://github.com/bankova/Databases.git View Raw File
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

class XSDValidation
{
    private static bool isValid=true;

    static void Main()
    {
        string xsdFilePathInvalid = "../../catalogueInvalid.xsd";
        string xmlFilePathInvalid = "../../catalogueInvalidxml.xml";
        string xsdFilePathValid = "../../catalogue.xsd";
        string xmlFilePathValid = "../../catalogue.xml";

        ValidateXmlAgainstXSD(xsdFilePathValid, xmlFilePathValid);
        ValidateXmlAgainstXSD(xsdFilePathInvalid, xmlFilePathInvalid);
    }

    private static void ValidateXmlAgainstXSD(string xsdFilePath, string xmlFilePath)
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(null, xsdFilePath);
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += Handler;
        XmlDocument document = new XmlDocument();
        document.Load(xmlFilePath);
        XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);

        while (rdr.Read())
        {

        }

        if (isValid)
        {
            Console.WriteLine("The document {0} validated against {1} is valid.", xmlFilePath, xsdFilePath);
        }
        else
        {
            Console.WriteLine("The document {0} validated against {1} is not valid.", xmlFilePath, xsdFilePath);
        }
    }

    private static void Handler(object sender, ValidationEventArgs e)
    {
        isValid = false;
        if (e.Severity == XmlSeverityType.Error || e.Severity ==
            XmlSeverityType.Warning)
            System.Diagnostics.Trace.WriteLine(
                String.Format("Line: {0}, Position: {1} \"{2}\"",
                    e.Exception.LineNumber, e.Exception.LinePosition,
    e.Exception.Message));
    }
}
Back to Top