在C#中针对引用的XSDvalidationXML

我有一个具有指定架构位置的XML文件,例如:

xsi:schemaLocation="someurl ..\localSchemaPath.xsd" 

我想在C#中validation。 Visual Studio,当我打开文件,对模式进行validation,并完美列出错误。 但不知何故,我似乎无法自动validation它在C#中没有指定模式来validation,像这样:

 XmlDocument asset = new XmlDocument(); XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath"); XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler); asset.Schemas.Add(schema); asset.Load(filename); asset.Validate(DocumentValidationHandler); 

我不应该能够自动使用XML文件中指定的模式进行validation吗? 我错过了什么?

6 Solutions collect form web for “在C#中针对引用的XSDvalidationXML”

您需要创build一个XmlReaderSettings实例,并在创buildXmlReader时将其传递给您的XmlReader。 然后,您可以在设置中订阅ValidationEventHandler以接收validation错误。 你的代码最终会看起来像这样:

 using System.Xml; using System.Xml.Schema; using System.IO; public class ValidXSD { public static void Main() { // Set the validation settings. XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Create the XmlReader object. XmlReader reader = XmlReader.Create("inlineSchema.xml", settings); // Parse the file. while (reader.Read()) ; } // Display any warnings or errors. private static void ValidationCallBack(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message); else Console.WriteLine("\tValidation error: " + args.Message); } } 

如果您使用.NET 3.5,更简单的方法是使用XDocumentXmlSchemaSetvalidation。

 XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(schemaNamespace, schemaFileName); XDocument doc = XDocument.Load(filename); string msg = ""; doc.Validate(schemas, (o, e) => { msg += e.Message + Environment.NewLine; }); Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg); 

请参阅MSDN文档以获取更多帮助。

以下示例validationXML文件并生成相应的错误或警告。

 using System; using System.IO; using System.Xml; using System.Xml.Schema; public class Sample { public static void Main() { //Load the XmlSchemaSet. XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add("urn:bookstore-schema", "books.xsd"); //Validate the file using the schema stored in the schema set. //Any elements belonging to the namespace "urn:cd-schema" generate //a warning because there is no schema matching that namespace. Validate("store.xml", schemaSet); Console.ReadLine(); } private static void Validate(String filename, XmlSchemaSet schemaSet) { Console.WriteLine(); Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString()); XmlSchema compiledSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { compiledSchema = schema; } XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(compiledSchema); settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); settings.ValidationType = ValidationType.Schema; //Create the schema validating reader. XmlReader vreader = XmlReader.Create(filename, settings); while (vreader.Read()) { } //Close the reader. vreader.Close(); } //Display any warnings or errors. private static void ValidationCallBack(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message); else Console.WriteLine("\tValidation error: " + args.Message); } } 

上例使用以下input文件。

 <?xml version='1.0'?> <bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema"> <book genre="novel"> <title>The Confidence Man</title> <price>11.99</price> </book> <cd:cd> <title>Americana</title> <cd:artist>Offspring</cd:artist> <price>16.95</price> </cd:cd> </bookstore> 

books.xsd

 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema"> <xsd:element name="bookstore" type="bookstoreType"/> <xsd:complexType name="bookstoreType"> <xsd:sequence maxOccurs="unbounded"> <xsd:element name="book" type="bookType"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="bookType"> <xsd:sequence> <xsd:element name="title" type="xsd:string"/> <xsd:element name="author" type="authorName"/> <xsd:element name="price" type="xsd:decimal"/> </xsd:sequence> <xsd:attribute name="genre" type="xsd:string"/> </xsd:complexType> <xsd:complexType name="authorName"> <xsd:sequence> <xsd:element name="first-name" type="xsd:string"/> <xsd:element name="last-name" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:schema> 

我在VB中做了这种自动validation,这就是我如何做到的(转换为C#):

 XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = settings.ValidationFlags | Schema.XmlSchemaValidationFlags.ProcessSchemaLocation; XmlReader XMLvalidator = XmlReader.Create(reader, settings); 

然后我在阅读文件时订阅了settings.ValidationEventHandler事件。

我个人喜欢validation没有callback:

 public bool ValidateSchema(string xmlPath, string xsdPath) { XmlDocument xml = new XmlDocument(); xml.Load(xmlPath); xml.Schemas.Add(null, xsdPath); try { xml.Validate(null); } catch (XmlSchemaValidationException) { return false; } return true; } 

(请参阅同步XML模式validation?.NET 3.5中的 Timiz0r的文章)

MSDN的例子使用LINQ to XML

  • 是否有可能从JAXB注释类生成XSD?
  • 当另一个元素有一定的值时,在XSD中需要XML元素吗?
  • 如何解决“无法find元素/属性<xxx>的模式信息?
  • 当没有互联网连接时,Spring schemaLocation失败
  • XSD中元素的ref属性是做什么的?
  • targetNamespace和xmlns没有前缀,有什么区别?
  • nillable和minOccurs XSD元素属性
  • xsd:include和xsd:import有什么区别?
  • 在Visual Studio IDE中自动生成XSD到C#
  • 如何从Eclipse中的XML文件生成XSD?
  • cvc-complex-type.2.4.a:从元素“init-param”开始find无效内容