gpt4 book ai didi

c# - XmlSerializer 不使用在类上定义的 XmlRoot

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:58 25 4
gpt4 key购买 nike

我正在尝试将自定义类序列化为 XML。这是类(class):

[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!

最佳答案

但是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无关.除非您出于其他目的需要它,否则可以将其删除。

关于c# - XmlSerializer 不使用在类上定义的 XmlRoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com