Validating XML against an XSD Schema

May 6, 2010 14:33 by bryan

When handling XML files you are going to need to validate the XML, and the best way, currently, is to use an XSD Schema.  It took me a little while to work out how to do this, and with help from Assaf Lavie I finally came up with a method to validate two streams, one holding the XML the other the XSD.

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
public void Validate(Stream xml, Stream xsd)
        {
            if (xml == null)
            {
                throw new ArgumentNullException("xml");
            }


            if (xsd == null)
            {
                throw new ArgumentNullException("xsd");
            }


            xml.Seek(0, SeekOrigin.Begin);
            var readerXML = new StreamReader(xml);
            string textXML = readerXML.ReadToEnd();


            if (string.IsNullOrEmpty(textXML))
            {
                throw new ArgumentNullException("xml need to hold some information");
            }


            xsd.Seek(0, SeekOrigin.Begin);
            var readerXSD = new StreamReader(xsd);
            string textXSD = readerXSD.ReadToEnd();


            if (string.IsNullOrEmpty(textXSD))
            {
                throw new ArgumentNullException("xsd need to hold some information");
            }


            try
            {
                // 1- Set the streams to the beginning
                xml.Seek(0, SeekOrigin.Begin);
                xsd.Seek(0, SeekOrigin.Begin);


                var errorMessages = new List<string>();


                // 2- Read XML file content 
                var xmlReader = new XmlTextReader(xml);


                // 3- Read Schema file content 
                StreamReader schemaReader = new StreamReader(xsd);


                // 4- Set Schema object by calling XmlSchema.Read() method 
                XmlSchema Schema = XmlSchema.Read(schemaReader, (o, e) =>
                    {
                        errorMessages.Add(e.Message);
                    });


                // 5- Create a new instance of XmlReaderSettings object 
                XmlReaderSettings readerSettings = new XmlReaderSettings();


                // 6- Set ValidationType for XmlReaderSettings object 
                readerSettings.ValidationType = ValidationType.Schema;


                // 7- Add Schema to XmlReaderSettings Schemas collection 
                readerSettings.Schemas.Add(Schema);


                // 8- Add your ValidationEventHandler address to 
                // XmlReaderSettings ValidationEventHandler 
                readerSettings.ValidationEventHandler += (o, e) =>
                    {
                        errorMessages.Add(e.Message);
                    };


                // 9- Create a new instance of XmlReader object 
                XmlReader objXmlReader = XmlReader.Create(xmlReader, readerSettings);


                // 10- Read XML content in a loop 
                while (objXmlReader.Read())
                { /*Empty loop*/}


                // 11- Raise exception, if XML validation fails
                if (errorMessages.Count() > 0)
                {
                    throw new Exception(string.Join("\r\n", errorMessages.ToArray()));
                }
            }
            catch (XmlException XmlExp)
            {
                throw new XMLValidationException(XmlExp.Message, XmlExp);
            }
            catch (XmlSchemaException XmlSchExp)
            {
                throw new XMLValidationException(XmlSchExp.Message, XmlSchExp);
            }
            catch (Exception GenExp)
            {
                throw;
            }


            finally
            {
                xml.Seek(0, SeekOrigin.Begin);
                xsd.Seek(0, SeekOrigin.Begin);
            }
        }


The need to generate an XSD from XML

April 28, 2010 15:30 by bryan

I came across a very simple to use XML to XSD generator today

http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx