您可以围绕 a 编写一个包装器XmlReader
,它会过滤掉后续的 xml 处理指令和文档类型。
public class XmlFilteringReader : XmlReader
{
private readonly XmlReader _source;
private bool _gotXmlDeclaration = false;
private bool _gotDoctype = false;
public XmlFilteringReader(XmlReader source)
{
_source = source;
}
public override bool Read()
{
var ok = _source.Read();
if (ok && _source.NodeType == XmlNodeType.ProcessingInstruction
&& _source.LocalName == "xml")
{
if (_gotXmlDeclaration) return Read(); // Recursive
_gotXmlDeclaration = true;
}
else if (ok && _source.NodeType == XmlNodeType.DocumentType)
{
if (_gotDoctype) return Read(); // Recursive
_gotDoctype = true;
}
return ok;
}
// Implementation of other methods and properties
// by calling the same method or property on _source
}
var serializer = new XmlSerializer(response.GetType());
var reader = new XmlFilteringReader(new XmlTextReader(stream) {XmlResolver = null});
var result = (IResponse) serializer.Deserialize(reader);
可以通过使用 Mvp.Xml 库来XmlWrappingReader
简化实现。还有一篇关于此的博客文章。