将格式不太好的 XML 加载到 XDocument(多个 DTD)
我在处理数据时遇到问题,该数据几乎是格式良好的 XHTML 文档,只不过它在开头有多个 DTD 声明:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body>
...
</body>
</html>
我需要仅使用 first DTD 和 将此数据加载到 XDocument 对象中忽略其余声明。完全忽略 DTD 处理是不可能的,因为文档可能包含不寻常的字符,例如 â
或 €
等。
文本是从外部源检索的我不知道为什么会这样。
显然,我天真的尝试加载此文档失败了,并出现 System.Xml.XmlException : Cannot have multiple DTDs
:
var xmlReaderSettings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlPreloadedResolver(),
ConformanceLevel = ConformanceLevel.Document,
};
using (var xmlReader = XmlReader.Create(stream, xmlReaderSettings))
{
return XDocument.Load(xmlReader);
}
处理此类数据的最佳方法是什么?
PS:我忘了提及,数据来自 Stream
,这可能会或可能不会使字符串操作变得更加复杂
I have got a problem handling data which is almost well-formed XHTML document except for it has multiple DTD declarations in the beginning:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body>
...
</body>
</html>
I need load this data into XDocument object using only the first DTD and ignoring the rest declarations. It is not possible to completely ignore DTD processing because the document may have unusual characters like â
or €
etc.
The text is retrieved from an external source and I have no idea why it comes like this.
Obviously my naive attempt to load this document fails with System.Xml.XmlException : Cannot have multiple DTDs
:
var xmlReaderSettings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlPreloadedResolver(),
ConformanceLevel = ConformanceLevel.Document,
};
using (var xmlReader = XmlReader.Create(stream, xmlReaderSettings))
{
return XDocument.Load(xmlReader);
}
What would be the best way to handle this kind of data?
P.S: I forgot to mention, that the data comes from a Stream
which may or may not make the string manipulation a little bit more complex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定是否有 XmlReader 设置可以忽略此问题,但您始终可以使用标准字符串操作来删除额外的文档类型。
I'm not sure if there's an XmlReader setting that will ignore this problem, but you could always use standard string manipulation to remove the extra doctypes.