XmlReader throws multiple DTDs error

无人久伴 提交于 2020-02-06 03:22:43

问题


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);

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.

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

It seems that XmlReader has hard time using an XmlParserContext.


回答1:


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;

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

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).

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.



来源:https://stackoverflow.com/questions/22516221/xmlreader-throws-multiple-dtds-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!