简体   繁体   中英

Implement Xml validation using XSD schema

我有XSD文件字符串而不是路径,而XML文件字符串不是路径,如何检查XML是否像XSD文件一样处于正确的架构中,并检查错误计数并返回所有错误?

EDIT: In response to the comment.

I'm not sure what you mean by throws and exception ?

That C# code works as expected for me.

This is what I did:

1) I saved the code to this file:

C:\Temp\xml_test.cs

2) I compiled that code inside the Zeus IDE which gave the following compiler output:

csc.exe /debug /r:System.dll; "C:\Temp\xml_test.cs"

Microsoft (R) Visual C# Compiler version 4.0.30319.18408
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

3) That compile created this xml_test.exe file.

Directory of c:\temp

09/04/2014  09:30 AM 5,120 xml_test.exe

4) Running the xml_test.exe results in this output:

Data at the root level is invalid. Line 1, position 1.

Now the output from step 4) is not surprising since the xml used is this:

string xmlText = "some xml string";

and the schema used is this:

string xsdText = "some xml schema string";

Obviously that is not a valid XML string or XML schema and the resulting output suggests as much.

SECOND EDIT:

If the code is changed to uses a valid XML string:

// Load the xml string into a memory stream
string xmlText = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                 "<Test>" +
                 "</Test>";

and a matching schema:

        // Load the schema string into a memory stream
        string xsdText = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" +
                         "<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" +
                         "  <xs:element name=\"Test\" type=\"xs:string\" />" +
                         "</xs:schema>";

The code then validates the XML without errors as would be expected.

THIRD EDIT:

Add this flag to the settings to make it call the event handler and not throw and exception:

settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

Using this flag the XML is validated on load, which means this call can also be removed as it will just report the same errors reported by the load:

document.Validate(eventHandler)

Original Post Below:

Something like this should work:

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

class XPathValidation
{
    static void Main() {
        try {
            // Load the schema string into a memory stream
            string xsdText = "some xml schema string";
            MemoryStream xsd = new MemoryStream(Encoding.ASCII.GetBytes(xsdText));

            // create a schema using that memory stream
            ValidationEventHandler eventHandler = new ValidationEventHandler(Validation);
            XmlSchema schema = XmlSchema.Read(xsd, eventHandler);

            // create some settings using that schema
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(schema);
            settings.ValidationType = ValidationType.Schema;

            // Load the xml string into a memory stream
            string xmlText = "some xml string";
            MemoryStream xml = new MemoryStream(Encoding.ASCII.GetBytes(xmlText));

            // create a XML reader
            XmlReader reader = XmlReader.Create(xml, settings);

            // load the XML into a document
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            // validate the XML
            document.Validate(eventHandler);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }

    static void Validation(object sender, ValidationEventArgs e) {
        switch (e.Severity) {
            case XmlSeverityType.Error:
                Console.WriteLine("Error: {0}", e.Message);
                break;
            case XmlSeverityType.Warning:
                Console.WriteLine("Warning {0}", e.Message);
                break;
        }
    }
}

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