gpt4 book ai didi

c# - 加载到 XDocument 时如何解析实体?

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:52 25 4
gpt4 key购买 nike

我正在尝试将 XHTML 文档加载到 XDocument 中,但我收到了“对未声明实体的引用”异常。我需要解决像 ® 这样的实体和 » .

我相信我的文档格式正确,这是头部:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

当我执行 XDocument.Load(<StringReader>) 时是我抛出这些异常的时候。

最佳答案

这是 msdn 和博客帖子的协作。

        XDocument document;

using (var stringReader = new StringReader(output))
{
var settings = new XmlReaderSettings
{
ProhibitDtd = false,
XmlResolver = new LocalXhtmlXmlResolver(bool.Parse(ConfigurationManager.AppSettings["CacheDTDs"]))
};

document = XDocument.Load(XmlReader.Create(stringReader, settings));
}

private class LocalXhtmlXmlResolver : XmlUrlResolver
{
private static readonly Dictionary<string, Uri> KnownUris = new Dictionary<string, Uri>
{
{ "-//W3C//DTD XHTML 1.0 Strict//EN", new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd") },
{ "-//W3C XHTML 1.0 Transitional//EN", new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd") },
{ "-//W3C//DTD XHTML 1.0 Transitional//EN", new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd") },
{ "-//W3C XHTML 1.0 Frameset//EN", new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd") },
{ "-//W3C//DTD XHTML 1.1//EN", new Uri("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd") }
};

private bool enableHttpCaching;
private ICredentials credentials;

public LocalXhtmlXmlResolver(bool enableHttpCaching)
{
this.enableHttpCaching = enableHttpCaching;
}

public override Uri ResolveUri(Uri baseUri, string relativeUri)
{
Debug.WriteLineIf(!KnownUris.ContainsKey(relativeUri), "Could not find: " + relativeUri);

return KnownUris.ContainsKey(relativeUri) ? KnownUris[relativeUri] : base.ResolveUri(baseUri, relativeUri);
}

public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
if (absoluteUri == null)
{
throw new ArgumentNullException("absoluteUri");
}

//resolve resources from cache (if possible)
if (absoluteUri.Scheme == "http" && this.enableHttpCaching && (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream)))
{
var request = WebRequest.Create(absoluteUri);

request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);

if (this.credentials != null)
{
request.Credentials = this.credentials;
}

var response = request.GetResponse();

return response.GetResponseStream();
}

//otherwise use the default behavior of the XmlUrlResolver class (resolve resources from source)
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
}

关于c# - 加载到 XDocument 时如何解析实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1645767/

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