gpt4 book ai didi

c# - .NET:在验证/读取 XML 模式时阻止 Web 访问?

转载 作者:数据小太阳 更新时间:2023-10-29 02:32:16 30 4
gpt4 key购买 nike

我试图在使用 XML 模式验证 XML 文档时阻止 .NET Framework 访问 Web,因为我不希望它一直依赖于 Web 访问。为此,我特意为我在验证时使用的所有 XSD 创建了本地硬盘副本,但在加载其中一些模式时它仍然失败。

例如,这段代码失败了(但前提是我的机器从网络上拔掉):

using (Stream schemaStream = File.OpenRead(schemaFileName))
{
XmlSchema schema = XmlSchema.Read(schemaStream, ValidationCallBack);
xmlSchemaSet.Add(schema);
}

schemaFileName 指向 本地 存储的 xmldsig-core-schema.xsd 文件副本。我得到的异常(exception)是

System.Net.WebException: The remote name could not be resolved: 'www.w3.org'
Status: NameResolutionFailure
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId)
at System.Xml.DtdParser.ParseExternalSubset()
at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset)
at System.Xml.DtdParser.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace)
at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace)
at System.Xml.Schema.XmlSchema.Read(XmlReader reader, ValidationEventHandler validationEventHandler)
at System.Xml.Schema.XmlSchema.Read(Stream stream, ValidationEventHandler validationEventHandler)

我怀疑它仍在尝试从 www.w3.org 加载某些内容,可能是 DTD 架构 http://www.w3.org/2001/XMLSchema.dtd有什么办法可以防止这种情况发生吗?

最佳答案

嗯,结果比我想象的要简单。这Q/A给了我领先(并刷新了我的内存)。

我已经有了自己的 XmlResolver 实现,用于重新路由到 XSD 文件的本地副本,但现在我还需要在加载 XML 模式时将它用于 DTD:

using (Stream schemaStream = File.OpenRead(schemaFileName))
{
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.XmlResolver = myXmlNamespaceResolver;
xmlReaderSettings.ProhibitDtd = false;

using (XmlReader reader = XmlReader.Create(schemaStream, xmlReaderSettings))
{
XmlSchema schema = XmlSchema.Read(reader, ValidationCallBack);
xmlSchemaSet.Add(schema);
}
}

然后我需要下载 http://www.w3.org/2001/XMLSchema.dtd 的副本和 http://www.w3.org/2001/datatypes.dtd现在即使没有 Web 访问也能正常工作。

关于c# - .NET:在验证/读取 XML 模式时阻止 Web 访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5654257/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com