0

第三方供应商向我们提供了格式不正确的 XML。它有多个 XML 声明:

<?xml version="1.0" encoding="utf-16"?><!DOCTYPE bob />
<?xml version="1.0"?><!DOCTYPE jim>

<elements>
...
</elements

我的反序列化代码:

 var serializer = new XmlSerializer(response.GetType());

                reader = new XmlTextReader(stream) {XmlResolver = null};

                result = (IResponse) serializer.Deserialize(reader);

我遇到的问题是反序列化程序抱怨多个 XML 声明。有什么办法可以去掉声明,以便 XML 成功反序列化?

谢谢

4

1 回答 1

1

您可以围绕 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简化实现。还有一篇关于此的博客文章。

于 2012-07-09T11:17:22.310 回答