Getting started with XSD validation with C#

Posted by Rosarch on Stack Overflow See other posts from Stack Overflow or by Rosarch
Published on 2010-03-25T04:18:25Z Indexed on 2010/03/25 4:23 UTC
Read the original article Hit count: 444

Filed under:
|
|
|

Here is my first attempt at validating XML with XSD.

The XML file to be validated:

<?xml version="1.0" encoding="utf-8" ?>
<config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">
  <levelVariant>
    <filePath>SampleVariant</filePath>
  </levelVariant>
  <levelVariant>
    <filePath>LegendaryMode</filePath>
  </levelVariant>
  <levelVariant>
    <filePath>AmazingMode</filePath>
  </levelVariant>
</config>

The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="config">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="levelVariant">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="filePath" type="xs:anyURI">
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists?

The validation code in C#:

        public void SetURI(string uri)
        {
            XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml");

// begin confusion
            string schemaURI = toValidate.Attributes("xmlns").First().ToString() 
                                  + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString();
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("", XmlReader.Create( SOMETHING ));

            XDocument toValidateDoc = new XDocument(toValidate);
            toValidateDoc.Validate(schemas, null);
// end confusion

            root = toValidate;
        }

Any illumination would be appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about xsd