忽略DOCTYPE .dtd,但.dtd文件必须仍然存在

时间:2010-10-08 21:09:26

标签: c# xml dtd

我有一个处理HTTP请求的Web服务。它接收的文档有一个嵌入的DOCTYPE,它指定.dtd文件。我希望使用更新的XML架构验证文件,以便在较新的设备连接到我的服务时使用。

我可以成功忽略.dtd文件中的验证,但.dtd文件必须存在于我的本地硬盘上。我想删除这些过时的文件,但还没找到方法。

我正在处理的示例XML文档:

<?xml version="1.0" encoding="us-ascii" standalone="no"?>
<!DOCTYPE SomeMessage SYSTEM "SomeMessage.dtd">
<SomeMessage>data</SomeMessage>

我用来打开文档的功能:

private void LoadXmlDoc(XmlTextReader myXmlTextReader)
{
    XmlReaderSettings readerSettings = new XmlReaderSettings();
    readerSettings.ValidationType = ValidationType.Schema;
    readerSettings.Schemas.Add(null, MyGoodSchemaFile);
    readerSettings.DtdProcessing = DtdProcessing.Ignore;
    readerSettings.XmlResolver = null; // Added as a test.

    readerSettings.ValidationEventHandler += ValidationEventHandle;
    XmlReader myXmlReader = XmlReader.Create(myXmlTextReader, readerSettings);

    XmlDocument myXmlDocument = new XmlDocument();
    myXmlDocument.XmlResolver = null; // Added as a test.
    myXmlDocument.Load(myXmlReader); // Exception thrown here!
}

捕获的异常:

System.IO.FileNotFoundException: Could not find file 'c:\windows\system32\inetsrv\SomeMessage.dtd'.
File name: 'c:\windows\system32\inetsrv\SomeMessage.dtd'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

未使用SomeMessage.dtd文件的内容 - 我会根据需要忽略它。但是,必须存在虚拟文件“c:\ windows \ system32 \ inetsrv \ SomeMessage.dtd”,否则抛出异常。

我在Windows 7上运行,使用Visual Studio 2010和.Net 4.0

如何忽略embeded .dtd并且还不需要在我的计算机上安装虚拟.dtd文件?

1 个答案:

答案 0 :(得分:10)

解决方案是将底层XmlTextReader的XmlResolver设置为null。更改XmlReaderSettings.XmlResolver = null没有帮助,也没有设置XmlDocument.XmlResolver = null

以下是更正的功能:

private void LoadXmlDoc(XmlTextReader myXmlTextReader)
{
    // The next line is the fix!!!
    myXmlTextReader.XmlResolver = null;  // Don't require file in system32\inetsrv

    XmlReaderSettings readerSettings = new XmlReaderSettings();
    readerSettings.ValidationType = ValidationType.Schema;
    readerSettings.Schemas.Add(null, MyGoodSchemaFile);
    readerSettings.DtdProcessing = DtdProcessing.Ignore;
    readerSettings.XmlResolver = null; // Doesn't help

    readerSettings.ValidationEventHandler += ValidationEventHandle;
    XmlReader myXmlReader = XmlReader.Create(myXmlTextReader, readerSettings);

    XmlDocument myXmlDocument = new XmlDocument();
    myXmlDocument.XmlResolver = null; // Doesn't help
    myXmlDocument.Load(myXmlReader); // Load doc, no .dtd required on local disk
}