XmlSerializer不使用在类上定义的XmlRoot

时间:2016-06-06 15:35:10

标签: c# xml serialization xmlserializer

我正在尝试将自定义类序列化为XML。这是班级:

[Serializable()]
[XmlRoot("KVP")]
public class SerializableKeyValuePair<TKey, TValue>
{

    public SerializableKeyValuePair()
    { }

    public SerializableKeyValuePair(TKey key, TValue value)
    {
        Key = key;
        Value = value;
    }

    public TKey Key { get; set; }
    public TValue Value { get; set; }

}

以下是尝试序列化它的代码:

    var xmlWriter = new StringWriter();
    Type[] extraTypes = new Type[1] { typeof(SerializableKeyValuePair<string, string>) };
    var xmlSerializer = new XmlSerializer(typeof(List<SerializableKeyValuePair<string, string>>), extraTypes);
    xmlSerializer.Serialize(xmlWriter, functions);
    xmlRet = xmlWriter.ToString();

以下是实际结果:

<ArrayOfSerializableKeyValuePairOfStringString>
    <SerializableKeyValuePairOfStringString>
        <Key>Min</Key>
        <Value>Min</Value>
    </SerializableKeyValuePairOfStringString>
    <SerializableKeyValuePairOfStringString>
        <Key>MinAvgMax</Key>
        <Value>MinAvgMax</Value>
    </SerializableKeyValuePairOfStringString>
</ArrayOfSerializableKeyValuePairOfStringString>

我想看到的是以下内容,但它似乎没有使用我定义的XmlRoot。任何人都可以帮我弄清楚如何获得这种XML结构吗?

<ArrayOfKVP>
    <KVP>
        <Key>Min</Key>
        <Value>Min</Value>
    </KVP>
    <KVP>
        <Key>MinAvgMax</Key>
        <Value>MinAvgMax</Value>
    </KVP>
</ArrayOfKVP>

TIA!

2 个答案:

答案 0 :(得分:1)

SerializableKeyValuePair不是根,List<SerializableKeyValuePair<string, string>>是!

我认为您正在寻找XmlType

[XmlType("KVP")]
public class SerializableKeyValuePair<TKey, TValue>
{
    //...
}

如果您想更改列表的元素名称,可以在创建序列化程序时提供XmlRootAttribute

var serializer = new XmlSerializer(typeof(List<SerializableKeyValuePair<string, string>>), 
    null, extraTypes, new XmlRootAttribute("ArrayOfKVP"), string.Empty);

另外,SerializableXmlSerializer无关。除非你出于其他目的需要它,否则它可以删除。

答案 1 :(得分:0)

首先,您可以尝试在serializztion之前选择KVP数组

var xKVP = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals("car"));

var serializer = new XmlSerializer(typeof(SerializableKeyValuePair<string, string>));
using (var reader = xKVP.CreateReader())
{
    var result = (SerializableKeyValuePair<string, string>) serializer.Deserialize(reader);
    Console.WriteLine(result.Key);
    Console.WriteLine(result.Value);
}

另一种方法,你可以为你的KVP数组创建一个包装器

[XmlRoot("ArrayOfKVP")]    
class ArrayOfKVP
{
    public ArrayOfKVP() {}

    [XmlElement("KVP")]
    public List<Foo> KVPList {get; set;}
}

[Serializable()]
[XmlType("KVP")]
public class SerializableKeyValuePair<TKey, TValue>
{

    public SerializableKeyValuePair()
    { }

    public SerializableKeyValuePair(TKey key, TValue value)
    {
        Key = key;
        Value = value;
    }

    public TKey Key { get; set; }
    public TValue Value { get; set; }
}