PageRenderTime 61ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 17ms app.codeStats 0ms

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

https://github.com/bankova/Databases
C# | 61 lines | 53 code | 8 blank | 0 comment | 5 complexity | be00620aa8d4bc5a49beefc94375a497 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Text;
 6using System.Threading.Tasks;
 7using System.Xml;
 8using System.Xml.Linq;
 9using System.Xml.Schema;
10
11class XSDValidation
12{
13    private static bool isValid=true;
14
15    static void Main()
16    {
17        string xsdFilePathInvalid = "../../catalogueInvalid.xsd";
18        string xmlFilePathInvalid = "../../catalogueInvalidxml.xml";
19        string xsdFilePathValid = "../../catalogue.xsd";
20        string xmlFilePathValid = "../../catalogue.xml";
21
22        ValidateXmlAgainstXSD(xsdFilePathValid, xmlFilePathValid);
23        ValidateXmlAgainstXSD(xsdFilePathInvalid, xmlFilePathInvalid);
24    }
25
26    private static void ValidateXmlAgainstXSD(string xsdFilePath, string xmlFilePath)
27    {
28        XmlReaderSettings settings = new XmlReaderSettings();
29        settings.Schemas.Add(null, xsdFilePath);
30        settings.ValidationType = ValidationType.Schema;
31        settings.ValidationEventHandler += Handler;
32        XmlDocument document = new XmlDocument();
33        document.Load(xmlFilePath);
34        XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
35
36        while (rdr.Read())
37        {
38
39        }
40
41        if (isValid)
42        {
43            Console.WriteLine("The document {0} validated against {1} is valid.", xmlFilePath, xsdFilePath);
44        }
45        else
46        {
47            Console.WriteLine("The document {0} validated against {1} is not valid.", xmlFilePath, xsdFilePath);
48        }
49    }
50
51    private static void Handler(object sender, ValidationEventArgs e)
52    {
53        isValid = false;
54        if (e.Severity == XmlSeverityType.Error || e.Severity ==
55            XmlSeverityType.Warning)
56            System.Diagnostics.Trace.WriteLine(
57                String.Format("Line: {0}, Position: {1} \"{2}\"",
58                    e.Exception.LineNumber, e.Exception.LinePosition,
59    e.Exception.Message));
60    }
61}