CodeGo.net>如何使用XmlSerializer反序列化大型文档中的节点

我有一个很大的XML文档,已加载到XmlDocument中,并且我想使用XmlSerializer类将其中的选定元素反序列化为使用xsd.exe生成的.NET类.

这是到目前为止我已经尝试过的MCVE; xsd和生成的类在帖子的末尾.如代码中的注释中所述,我收到了InvalidOperationException-< Cars xmlns:'http:// MyNamespace'/>没想到:

static string XmlContent = @"
    <RootNode xmlns=""http://MyNamespace"">
        <Cars>
        <Car make=""Volkswagen"" />
        <Car make=""Ford"" />
        <Car make=""Opel"" />
        </Cars>
    </RootNode>";

static void TestMcve()
{
    var doc = new XmlDocument();
    doc.LoadXml(XmlContent);
    var nsMgr = new XmlNamespaceManager(doc.NameTable);
    nsMgr.AddNamespace("myns", "http://MyNamespace");
    var rootSerializer = new XmlSerializer(typeof(RootNode));
    var root = (RootNode) rootSerializer.Deserialize(new XmlNodeReader(doc));
    Console.WriteLine(root.Cars[0].make); // Works fine so far

    var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr);
    Console.WriteLine(node.OuterXml);
    var carSerializer = new XmlSerializer(typeof(Car));
    using (var reader = new XmlNodeReader(node))
    {
        // What I want is a list of Car instances deserialized from
        // the Car child elements of the Cars element.
        // The following line throws an InvalidOperationException
        // "<Cars xmlns:'http://MyNamespace' /> was not expected"
        // If I change SelectSingleNode above to select "myns:Cars/myns:Car"
        // I get "<Car xmlns:'http://MyNamespace' /> was not expected"
        var result = carSerializer.Deserialize(reader);
    }
}

我还希望随后更新我的Car类实例,并使用XmlSerializer将其重新插入文档中,该问题是后续问题How to insert a node in a large document using XmlSerializer
的主题.

xsd和生成的类如下:

<xs:schema xmlns="http://MyNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           targetNamespace="http://MyNamespace" 
           elementFormDefault="qualified" attributeFormDefault="unqualified" 
           version="3.9.0.8">
  <xs:complexType name="Cars">
    <xs:sequence>
      <xs:element name="Car" type="Car" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="Car">
    <xs:attribute name="make" type="xs:string" use="required"/>
  </xs:complexType>
  <xs:complexType name="RootNode">
    <xs:sequence>
      <xs:element name="Cars" type="Cars" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
  <xs:element name="RootNode" type="RootNode" />
</xs:schema>

xsd.exe生成的代码:

using System.Xml.Serialization;


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://MyNamespace", IsNullable=false)]
public partial class RootNode {

    private Car[] carsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
    public Car[] Cars {
        get {
            return this.carsField;
        }
        set {
            this.carsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
public partial class Car {

    private string makeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string make {
        get {
            return this.makeField;
        }
        set {
            this.makeField = value;
        }
    }
}
最佳答案
您在这里有两个问题:

> var节点= doc.DocumentElement.SelectSingleNode(“ myns:Cars”,nsMgr);位于< Cars> element-用于重复< Car>的容器元素节点-但是您的XmlSerializer构造为反序列化名为< Car>的单个根元素.尝试使用构造为对单个汽车进行反序列化的序列化器对汽车序列进行反序列化将不起作用.
>由于某种原因,xsd.exe为您的Car类型生成了一个没有XmlRoot属性的定义:

[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://MyNamespace")]
// Not included!
//[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://MyNamespace")]
public partial class Car
{
}

因此,如果您尝试序列化或反序列化Car的单个实例作为XML文档的根XML元素,则XmlSerializer会期望该根元素不在任何命名空间中.每个< Car>大文档中的“节点”位于默认的“ http:// MyNamespace”命名空间中,因此尝试对每个序列进行反序列化也将无效.

您可以手动将缺少的[XmlRoot(Namespace =“ http:// MyNamespace”)]属性添加到Car中,但是如果随后修改了XSD文件并且需要重新生成c#类型,则必须这样做是很麻烦的.

为避免这两个问题,您可以使用XmlNode.SelectNodes(String, XmlNamespaceManager)选择每个< Car> < Cars>内部的节点元素,然后使用重写XmlRootAttribute通过constructing an XmlSerializer对每个元素进行反序列化,其中包含要反序列化的节点的元素名称和名称空间.首先,定义以下扩展方法:

public static partial class XmlNodeExtensions
{
    public static List<T> DeserializeList<T>(this XmlNodeList nodes)
    {
        return nodes.Cast<XmlNode>().Select(n => n.Deserialize<T>()).ToList();
    }

    public static T Deserialize<T>(this XmlNode node)
    {
        if (node == null)
            return default(T);
        var serializer = XmlSerializerFactory.Create(typeof(T), node.LocalName, node.NamespaceURI);
        using (var reader = new XmlNodeReader(node))
        {
            return (T)serializer.Deserialize(reader);
        }
    }
}

public static class XmlSerializerFactory
{
    // To avoid a memory leak the serializer must be cached.
    // https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer
    // This factory taken from 
    // https://stackoverflow.com/questions/34128757/wrap-properties-with-cdata-section-xml-serialization-c-sharp/34138648#34138648

    readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
    readonly static object padlock;

    static XmlSerializerFactory()
    {
        padlock = new object();
        cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
    }

    public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
    {
        if (serializedType == null)
            throw new ArgumentNullException();
        if (rootName == null && rootNamespace == null)
            return new XmlSerializer(serializedType);
        lock (padlock)
        {
            XmlSerializer serializer;
            var key = Tuple.Create(serializedType, rootName, rootNamespace);
            if (!cache.TryGetValue(key, out serializer))
                cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
            return serializer;
        }
    }
}

然后反序列化如下:

var nodes = doc.DocumentElement.SelectNodes("myns:Cars/myns:Car", nsMgr);
var cars = nodes.DeserializeList<Car>();

必须缓存具有重写根元素名称或名称空间构造的序列化程序的节点,以避免内存泄漏,如this answerMarc Gravell所述.

样本工作.Net fiddle.

转载注明原文:CodeGo.net>如何使用XmlSerializer反序列化大型文档中的节点 - 代码日志