C# 根据C中引用的XSD验证XML#
我有一个具有指定架构位置的XML文件,例如:C# 根据C中引用的XSD验证XML#,c#,xml,xsd,C#,Xml,Xsd,我有一个具有指定架构位置的XML文件,例如: xsi:schemaLocation="someurl ..\localSchemaPath.xsd" 我想在C#中进行验证。当我打开文件时,VisualStudio会根据模式对其进行验证,并完美地列出错误。然而,不知何故,如果不指定要验证的模式,我似乎无法在C#中自动验证它,例如: XmlDocument asset = new XmlDocument(); XmlTextReader schemaReader = new XmlTextRea
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
我想在C#中进行验证。当我打开文件时,VisualStudio会根据模式对其进行验证,并完美地列出错误。然而,不知何故,如果不指定要验证的模式,我似乎无法在C#中自动验证它,例如:
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文件中指定的模式自动进行验证吗?我遗漏了什么?我在VB中进行了这种自动验证,我就是这样做的(转换为C#):
然后,我在读取文件时订阅了
设置.ValidationEventHandler
事件。您需要创建一个XmlReaderSettings实例,并在创建时将其传递给XmlReader。然后,您可以订阅设置中的ValidationEventHandler
,以接收验证错误。您的代码最终将如下所示:
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);
}
}
以下内容验证XML文件并生成相应的错误或警告
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);
}
}
前面的示例使用以下输入文件
<?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>
自信的人
11.99
美洲人
后代
16.95
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>
如果您使用的是.NET 3.5,一种更简单的方法是使用
XDocument
和XmlSchemaSet
验证
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);
请参阅以获取更多帮助。就我个人而言,我倾向于在不回调的情况下进行验证:
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;
}
(参见Timiz0r的帖子)+1尽管为了完整性,应该更新为使用
using
子句:)如果您希望与XSD文件进行比较,请在上面的代码中添加以下行:settings.Schemas.add(“YourDomainHere”,“yourXSDFile.XSD”);要获取错误的行和位置,只需使用:args.Exception.LineNumber。。。在ValidationCallback中,如果我的架构没有名称空间怎么办?使用lambda,更好的IMHO,更清晰的代码settings.ValidationEventHandler+=(o,args)=>{errors=true;//更多代码}代码>参考MSDN示例:该方法要求您事先知道模式,而不是从xml中获取内联模式。这可以正常工作,但当xml文档包含一些html标记(如my new catalog)时会出错。。。。在上面的例子中,像“”这样的html标记会产生一个问题,因为它是“”的值。。。如何验证it@AnilPurswani:如果希望将HTML放入XML文档中,则需要将其包装在CDATA中<代码>新目录…]]>
是正确的方法。简单而优雅!这在针对固定模式集进行验证时非常有效(这是我们的情况,是一个包含多个文件夹和文件的大型模式集)。我已经在考虑缓存XmlSchemaSet,以便在对验证器的调用之间重用。谢谢!回调为您提供了一些关于xml中哪一行不正确的额外信息。此方法是非常二进制的,无论是对的还是错的:)您可以获得异常消息:)
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;
}