JL.*_*JL. 11 c# xml schema xsd xml-validation
我有运行时读入的xml文件,是否可以在运行时针对xsd文件验证xml?使用c#
Joh*_*ers 15
试试这个:
public void ValidateXmlDocument(
XmlReader documentToValidate, string schemaPath)
{
XmlSchema schema;
using (var schemaReader = XmlReader.Create(schemaPath))
{
schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
}
var schemas = new XmlSchemaSet();
schemas.Add(schema);
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemas;
settings.ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += ValidationEventHandler;
using (var validationReader = XmlReader.Create(documentToValidate, settings))
{
while (validationReader.Read())
{
}
}
}
private static void ValidationEventHandler(
object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
throw args.Exception;
}
Debug.WriteLine(args.Message);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我的代码太多了!我在测试中使用它:
public static bool IsValid(XElement element, params string[] schemas)
{
XmlSchemaSet xsd = new XmlSchemaSet();
XmlReader xr = null;
foreach (string s in schemas)
{ // eh, leak 'em.
xr = XmlReader.Create(
new MemoryStream(Encoding.Default.GetBytes(s)));
xsd.Add(null, xr);
}
XDocument doc = new XDocument(element);
var errored = false;
doc.Validate(xsd, (o, e) => errored = true);
if (errored)
return false;
// If this doesn't fail, there's an issue with the XSD.
XNamespace xn = XNamespace.Get(
element.GetDefaultNamespace().NamespaceName);
XElement fail = new XElement(xn + "omgwtflolj/k");
fail.SetAttributeValue("xmlns", xn.NamespaceName);
doc = new XDocument(fail);
var fired = false;
doc.Validate(xsd, (o, e) => fired = true);
return fired;
}
Run Code Online (Sandbox Code Playgroud)
这个将模式作为字符串(程序集中的文件资源)接收,并将它们添加到模式集中.我验证,如果它无效,我返回false.
如果发现xml无效,我会进行否定检查以确保我的模式没有搞砸.它不能保证万无一失,但我用它来查找我的模式中的错误.
归档时间: |
|
查看次数: |
11900 次 |
最近记录: |