XML Schema Validator Class (from UABv2.0)

这里有一个 XML 架构验证类,摘自 Microsoft Updater Application Block v2.0 。

**

源码:

**

//============================================================================================================
// Microsoft Updater Application Block for .NET
// http://msdn.microsoft.com/library/en-us/dnbda/html/updater.asp
//
// SchemaValidator.cs
//
// Contains the implementation of the schema validator.
//
// For more information see the Updater Application Block Implementation Overview.
//
//============================================================================================================
// Copyright ?Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//============================================================================================================

using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace Microsoft.ApplicationBlocks.Updater.Utilities
{
///

1<summary>   
2/// Helper class to perform schema validations.   
3/// </summary>

public sealed class SchemaValidator
{
#region Private members

///

1<summary>   
2/// The schemas that will be used for validation.   
3/// </summary>

private ArrayList schemas = new ArrayList(2);

///

1<summary>   
2/// The errors detected during the validation.   
3/// </summary>

private ArrayList errors = new ArrayList(5);

///

1<summary>   
2/// Whether the document is valid or not.   
3/// </summary>

private bool isValid;

#endregion

#region Constructors

///

1<summary>   
2/// Creates an instance of the SchemaValidator using the document and the schemas.   
3/// </summary>

///

1<param name="document"/>

The document to validate.
///

1<param name="schemas"/>

A list of schemas to validate the document against.
public SchemaValidator( string document, params Stream[] schemas )
{
this.schemas.Add( document );
foreach(Stream s in schemas)
{
this.schemas.Add( s );
}
isValid = true;
}

#endregion

#region Public members

///

1<summary>   
2/// Validates the document and returns the result of the validation.   
3/// </summary>

///

1<returns><c>true</c> if the document have succeeded the validation, otherwise <c>false</c>.</returns>

public bool Validate()
{
errors.Clear();
XmlValidatingReader vr = null;
object doc = schemas[0];
if ( doc is Stream)
{
vr = new XmlValidatingReader( (Stream)doc, XmlNodeType.Element, null );
}
else if ( doc is String )
{
vr = new XmlValidatingReader( (string)doc, XmlNodeType.Element, null );
}

try
{
for(int i=1;i

 1<schemas.count;i++) (stream)schemas[i]="" )="" );="" +="new" <summary="" finally="" isvalid;="" new="" null,="" return="" system.xml.schema.validationeventhandler(validationeventhandler);="" vr.close();="" vr.read()="" vr.schemas.add(="" vr.validationeventhandler="" while(="" xmltextreader(="" {="" }="">   
 2/// Contains the validation errors encountered in the last validation operation.   
 3///    
 4public ValidationEventArgs[] Errors   
 5{   
 6get   
 7{   
 8return (ValidationEventArgs[])errors.ToArray(typeof(ValidationEventArgs) );   
 9}   
10} 
11
12/// <summary>   
13/// Helper method to capture the event handlers.   
14/// </summary>   
15/// <param name="sender"/>The sender of the event.   
16/// <param name="e"/>The information about the event.   
17private void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)   
18{   
19errors.Add( e );   
20if ( e.Severity == XmlSeverityType.Warning )   
21{   
22return;   
23}   
24isValid = false;   
25} 
26
27#endregion   
28}   
29}   
30
31
32###  使用: 
33
34/// <summary>   
35/// Download and validates the manifest using the Uri location.   
36/// </summary>   
37/// <param name="type"/>The type that represents the manifest class.   
38/// <param name="location"/>The location of the manifest.   
39/// <param name="schemaResource"/>The resource where the embedded XSD resides in the assembly.   
40/// <returns>The Manifest instance.</returns>   
41[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]   
42private object ValidateAndDeserialize( Type type, Uri location, string schemaResource )   
43{   
44object result = null;   
45try   
46{   
47string doc = DownloadFile( location );   
48using ( Stream schema = Assembly.GetExecutingAssembly().GetManifestResourceStream( schemaResource ) )   
49{   
50SchemaValidator validator = new SchemaValidator( doc, schema );   
51if ( !validator.Validate() )   
52{   
53Logger.LogAndThrowException( new ApplicationUpdaterException( Resource.ResourceManager[ Resource.MessageKey.ManifestSchemaError, location, schemaResource ] ) );   
54} 
55
56XmlSerializer xser = new XmlSerializer( type );   
57result = xser.Deserialize( new XmlTextReader( doc, XmlNodeType.Document, null) );   
58}   
59}   
60catch( Exception ex )   
61{   
62Logger.LogAndThrowException( ex );   
63} 
64
65return result;   
66}</schemas.count;i++)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus