简体   繁体   中英

schema validation XML

I have an XSD file and an XML file, how can I check if the XML is in the right schema like the XSD file?

i know there is an validate function in the XmlDocument class, but it needs an event handler and all I need is true or false.

PS I'm working inVisual Studio 2010.

there is a much easy way to do it:

private void ValidationCallBack(object sender, ValidationEventArgs e)
{  
    throw new Exception();
}

public bool validate(string sxml)
{
    try
    {
        XmlDocument xmld=new XmlDocument ();
        xmld.LoadXml(sxml);
        xmld.Schemas.Add(null,@"c:\the file location");
        xmld.validate(ValidationCallBack);
        return true;
    }
    catch
    {
        return false;
    }
}

PS : I didn't wrote this in VS so there might be word that not in case sensitive, but this codes works!

You can create a validating XmlReader instance using the XmlReaderSettings class and the Create method.


private bool ValidateXml(string xmlFilePath, string schemaFilePath, string schemaNamespace, Type rootType)
{
    XmlSerializer serializer = new XmlSerializer(rootType);

    using (var fs = new StreamReader(xmlFilePath, Encoding.GetEncoding("iso-8859-1")))
    {
        object deserializedObject;
        var xmlReaderSettings = new XmlReaderSettings();
        if (File.Exists(schemaFilePath))
        {
            //select schema for validation  
            xmlReaderSettings.Schemas.Add(schemaNamespace, schemaPath); 
            xmlReaderSettings.ValidationType = ValidationType.Schema;
            try
            {
            using (var xmlReader = XmlReader.Create(fs, xmlReaderSettings))
            {                
                if (serializer.CanDeserialize(xmlReader))
                {
                    return true;
                    //deserializedObject = serializer.Deserialize(xmlReader);
                }
                else
                {
                    return false;
                }
            }
            }
            catch(Exception ex)
            { return false; }
        }
    }
}

The above code will throw an exception if the schema is invalid or it is unable to deserialize the xml. rootType is the type of the root element in the equivalent class hierarchy.


Schema at: XML Schema Tutorial . Schema at: XML Schema TutorialSave the file as D:\\SampleSchema.xsd .

Run xsd.exe :

  1. Open 'Start Menu > All Programs > Microsoft Visual Studio 2010 > Visual Studio Tools > Visual Studio 2010 Command Prompt'
  2. In the command prompt, type: xsd.exe /c /out:D:\\ "D:\\SampleSchema.xsd"
  3. xsd options: /out option is to specify the output directory, /c is to specify the tool to generate classes
  4. The output class hierarchy is present at D:\\SampleSchema.cs
  5. The generated class hierarchy looks some thing like this,

//------------------------------------------------------------------------------
// 
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4952
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// 
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
// 


/// 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class note {

    private string toField;

    private string fromField;

    private string headingField;

    private string bodyField;

    /// 
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string to {
        get {
            return this.toField;
        }
        set {
            this.toField = value;
        }
    }

    /// 
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string from {
        get {
            return this.fromField;
        }
        set {
            this.fromField = value;
        }
    }

    /// 
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string heading {
        get {
            return this.headingField;
        }
        set {
            this.headingField = value;
        }
    }

    /// 
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string body {
        get {
            return this.bodyField;
        }
        set {
            this.bodyField = value;
        }
    }
}

Add the class to the visual studio project.
For the above xsd sample, the root class is note .
Call the method,


bool isXmlValid = ValidateXml(@"D:\Sample.xml", 
                              @"D:\SampleSchema.xsd", 
                              @"http://www.w3.org/2001/XMLSchema", 
                              typeof(note));

You could do something like this.

public class XmlValidator
{
    private bool _isValid = true;

    public bool Validate(string xml)
    {
        _isValid = true;

        // Set the validation settings as needed.
        var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema };
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += ValidationCallBack;

        var reader = XmlReader.Create(new StringReader(xml), settings);

        while(reader.Read())
        {
            // process the content if needed
        }

        return _isValid;
    }

    private void ValidationCallBack(object sender, ValidationEventArgs e)
    {
        // check for severity as needed
        if(e.Severity == XmlSeverityType.Error)
        {
            _isValid = false;
        }
    }
}

class Program
{

    static void Main(string[] args)
    {
        var validator = new XmlValidator();

        var result =
            validator.Validate(@"<?xml version=""1.0""?>
                 <Product ProductID=""1"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:noNamespaceSchemaLocation=""schema.xsd"">
                     <ProductName>Chairs</ProductName>
                 </Product>");

}

The schema.

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <xsd:element name="Product">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string"/>
         </xsd:sequence>
         <xsd:attribute name="ProductID" use="required" type="xsd:int"/>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

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