gpt4 book ai didi

c# - XmlSerializer 序列化子对象

转载 作者:行者123 更新时间:2023-11-30 15:12:39 24 4
gpt4 key购买 nike

你如何序列化以下内容

[XmlRoot("response")]
public class MyCollection<T>
{
[XmlElement("person", Type = typeof(Person))]
public List<T> entry;
public int startIndex;
}

其中 T 可以是类

public class Person
{
public string name;
}

进入

<response>
<startIndex>1</startIndex>
<entry>
<person>
<name>meeee</name>
</person>
</entry>
<entry>
<person>
<name>youuu</name>
</person>
</entry>
</response>

我一直在研究 [XmlArray]、[XmlArrayItem] 和 [XmlElement],但我似乎无法获得正确的组合。啊啊啊。

更新:

[XmlArray("entry")]
[XmlArrayItem("person", Type = typeof(Person))]
public List<T> entry;

给我

<entry><person></person><person></person></entry>


[XmlElement("person", Type = typeof(Person))]
public List<T> entry;

给我

<person></person><person></person>

最佳答案

我看不出有什么明显的方法可以在不彻底改变类的情况下让它输出这些结果……这可能不是你想要的,但是通过镜像所需的输出(在 DTO 中并不少见)它得到了正确的结果...

否则,您可能正在查看 IXmlSerializable,这是一个巨大的痛苦:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("response")]
public class MyResponse {
public MyResponse() {
Entries = new List<Entry>();
}
[XmlElement("startIndex", Order = 1)]
public int StartIndex { get; set; }
[XmlElement("entry", Order = 2)]
public List<Entry> Entries { get; set; }
}
public class Entry {
public Entry() { }
public Entry(Person person) { Person = person; }
[XmlElement("person")]
public Person Person { get; set; }
public static implicit operator Entry(Person person) {
return person == null ? null : new Entry(person);
}
public static implicit operator Person(Entry entry) {
return entry == null ? null : entry.Person;
}
}
public class Person {
[XmlElement("name")]
public string Name { get; set; }
}
static class Program {
static void Main() {
MyResponse resp = new MyResponse();
resp.StartIndex = 1;
resp.Entries.Add(new Person { Name = "meeee" });
resp.Entries.Add(new Person { Name = "youuu" });
XmlSerializer ser = new XmlSerializer(resp.GetType());
ser.Serialize(Console.Out, resp);
}
}

关于c# - XmlSerializer 序列化子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/985452/

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