代码如下
DataSet ds = new DataSet();
ds.ReadXmlSchema(Server.MapPath("~/App_Code/DataSet1.xsd"));
ds.ReadXml(Server.MapPath("Data.xml"), XmlReadMode.InferTypedSchema);
附使用xsd验证xml文档的代码,载自msdn(不再说明如何生成xsd)
xsd架构添加到 XmlReaderSettings 对象的 XmlSchemaSet Schemas 属性中。XmlReaderSettings 对象作为参数传递给需要验证的 XML 文档的 XmlReader 对象的 Create 方法。
XmlReaderSettings 对象的 ValidationType 属性设置为 Schema,强制通过 XmlReader 对象的 Create 方法验证 XML 文档。ValidationEventHander 添加到 XmlReaderSettings 对象中,以处理 XML 文档和架构的验证过程中发现的错误所引发的任何 Warning 或 Error 事件。
using System;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaSetExample
{
static void Main()
{
XmlReaderSettings booksSettings = new XmlReaderSettings();
booksSettings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
booksSettings.ValidationType = ValidationType.Schema;
booksSettings.ValidationEventHandler += new ValidationEventHandler(booksSettingsValidationEventHandler);
XmlReader books = XmlReader.Create("contosoBooks.xml", booksSettings);
while (books.Read()) { }
}
static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)
{
Console.Write("WARNING: ");
Console.WriteLine(e.Message);
}
else if (e.Severity == XmlSeverityType.Error)
{
Console.Write("ERROR: ");
Console.WriteLine(e.Message);
}
}
}