简体   繁体   中英

Validate XML with a XSD Schema without changing the XML using C#

I have an XML file without a Schema in the XML, and I need to validate the XML against a XSD schema. I have seen many examples where you inject the XSD in to the XML and then validate the XML. I don't want to change the XML, is it possible to validate the XML, against the schema without change the XML?

It's easy to code with a few lines in C#.

I created a simple command line interface utility that takes two parameters: XML, XSD and does verification.

You can download it here .

Here's the main code:

            // 1- Read XML file content
            reader = new XmlTextReader(XMLPath);

            // 2- Read Schema file content
            StreamReader SR = new StreamReader(XSDPath);

            // 3- Create a new instance of XmlSchema object
            XmlSchema Schema = new XmlSchema();
            // 4- Set Schema object by calling XmlSchema.Read() method
            Schema = XmlSchema.Read(SR,
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler));

            // 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 +=
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler);

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


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

You can add the schema to the xml doc

doc.Schemas.Add(schema);

And then validate it

bool xmlvalid = true;
string lastXmlError = "";

doc.Validate(new System.Xml.Schema.ValidationEventHandler(
    delegate(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == System.Xml.Schema.XmlSeverityType.Error)
            {
                xmlvalid = false;
                lastXmlError = args.Message;
            }
    }));

if (!xmlvalid)
   //raise error

Provide a ValidationEventHandler only if you want to keep validating the document beyond the first validation error. Otherwise, just do this:

private bool ValidateDocument(string xmlFile, string xsdFile)
{
    XmlReaderSettings settings = new XmlReaderSettings{ValidationType 
      = ValidationType.Schema};
    settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(xsdFile)));
    XmlReader reader = XmlReader.Create(xmlFile, settings);

    try
    {
        while(reader.Read());
        return true;
    }
    catch (XmlException ex) 
    {
        // XmlException indicates a validation error occurred.
        return false;
    }
}

The following links provide more information:

http://msdn.microsoft.com/en-us/library/1xe0740a.aspx

http://support.microsoft.com/kb/307379

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM