我无法验证序列化数据。
好的,所以我从一些第三方获得的XSD文件开始。使用xsd工具生成C#类。然后我添加了
[XmlAttribute("noNamespaceSchemaLocation", Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
public string SchemaLocation = "http://localhost/schemas/AP_Transactions_10052011.xsd";
到顶级对象。有问题的URL显然可以从我运行代码的机器上访问。然后我使用XmlSerializer
对其进行序列化,正确生成
<?xml version="1.0" encoding="utf-8"?>
<BU_AP_Vendor_Invoices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="http://local.com/schemas/AP_Transactions_10052011.xsd">
...
</BU_AP_Vendor_Invoices>
到目前为止一切顺利。 现在我试图像这样验证文件:
public static void Validate(TextReader xmlData)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += delegate(object sender, ValidationEventArgs args)
{
Console.WriteLine(args.Message);
};
using (XmlReader xmlReader = XmlReader.Create(xmlData, settings))
while (xmlReader.Read()) ;
}
对XML文件中的每个元素发出Could not find schema information for the element 'element name'
个警告。我认为这意味着XSD根本没有被加载。
我在查看XmlReaderSettings.Schemas
,但读者如何知道在那里添加什么?我假设如果我没有明确地添加模式,那么魔术就会发生,但这似乎不起作用。
问题是如何正确地做到这一点?