根据自己的架构引用验证XDocument实例

时间:2010-09-09 16:07:30

标签: xml validation schema linq-to-xml

我正在使用XDocument.Validate扩展方法来验证我的实例。无论如何要保持XML实例对其自己的模式引用负责吗?这似乎是相当含蓄的东西。不幸的是,只是将实例加载到XDocument中似乎不会隐式执行此验证。

1 个答案:

答案 0 :(得分:1)

如果要在加载时验证,请尝试使用:

XDocument.Load Method (XmlReader, LoadOptions)

验证XMLReader

例如,像这样:

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

ValidationEventHandler validator = delegate(object sender,
ValidationEventArgs e)
{
    Console.WriteLine("{0}: {1}", e.Severity, e.Message);
};
settings.ValidationEventHandler += validator;
settings.CloseInput = true;
StringReader sr = new StringReader(inputXml);
reader = XmlReader.Create(sr, settings);