XmlReader引发多个DTD错误 [英] XmlReader throws multiple DTDs error

查看:75
本文介绍了XmlReader引发多个DTD错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们要加载xml(cXML)并针对我们在本地存储的DTD进行验证。这是此代码:

Let's say we want to load an xml (cXML) and validate it against a DTD that we have stored locally. Here's the code for this:

XmlPreloadedResolver resolver = new XmlPreloadedResolver(XmlKnownDtds.None);
resolver.Add(new Uri(DocTypeSystemId), File.ReadAllText(@"C:\cXml.dtd"));
XmlReaderSettings settings = new XmlReaderSettings
{
    ValidationType = ValidationType.DTD,
    DtdProcessing = DtdProcessing.Parse             
};
settings.ValidationEventHandler += Settings_ValidationEventHandler;

XmlParserContext context = new XmlParserContext(null, null, "cXML", null, 
                               DocTypeSystemId, null, null, null, XmlSpace.None);

XmlReader reader = XmlReader.Create(stream, settings, context);
XDocument doc = XDocument.Load(reader);

不幸的是,如果cXML输入已经带有DTD定义,则XmlReader将抛出XmlException声明: 消息不能有多个DTD。第2行,位置1。

Unfortunately in case the cXML input already comes with a DTD definition, the XmlReader will throw an XmlException stating: Message Cannot have multiple DTDs. Line 2, position 1.

如果我们从输入中删除DOCTYPE,则会显示警告未找到DTD。 并且xml未被验证。

If we remove the DOCTYPE from the input a warning is shown No DTD found. and the xml isn't validated.

似乎XmlReader很难使用XmlParserContext。

It seems that XmlReader has hard time using an XmlParserContext.

推荐答案

相反,阅读器是过时的 XmlTextReader 的实例:

If instead the reader is an instance of the obsolete XmlTextReader:

XmlTextReader textReader = new XmlTextReader(stream, XmlNodeType.Document, context);
XmlValidatingReader reader = new XmlValidatingReader(textReader);
reader.ValidationType = ValidationType.DTD;
reader.ValidationEventHandler += Settings_ValidationEventHandler;

然后,多个DTD都没有例外,并且xml进行了验证。

Then there is no exception for multiple DTDs and the xml is validated.

很明显,XmlTextReader和XmlReader的功能有所不同。当xml缺少暂停验证的DOCTYPE时,它们似乎都输出警告。误解 XmlValidatingReaderImpl.ProcessCoreReaderEvent() DtdValidator.Validate()(其中 schemaInfo.SchemaType == SchemaType.DTD 为假,也许是因为它不存在DTD。)

Obviously there is a difference between how XmlTextReader and XmlReader function. They both seem to output a warning when the xml is missing a DOCTYPE which halts validation. The following calls are involved in the misunderstanding XmlValidatingReaderImpl.ProcessCoreReaderEvent() and DtdValidator.Validate() (where schemaInfo.SchemaType == SchemaType.DTD is false maybe because it's no DTD exists).

最好只是尝试在输入xml中更改/添加DOCTYPE元素,而不是与 XmlParserContext 和不同的阅读器实现作斗争。

With all this in mind it seems better to just try to change/add the DOCTYPE element in the input xml than battle with XmlParserContext and the different reader implementations.

这篇关于XmlReader引发多个DTD错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆