gpt4 book ai didi

c# - xml序列化——集合属性

转载 作者:行者123 更新时间:2023-11-30 21:12:54 25 4
gpt4 key购买 nike

你好,

这段代码:

[Serializable]
[XmlRoot("A")]
public class A
{
public B B { get; set; }

public void Save()
{
string settingsFilePath = string.Format("test.xml");
XmlSerializer serializer = new XmlSerializer(typeof(A));
TextWriter writer = new StreamWriter(settingsFilePath);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty) });
serializer.Serialize(writer, this, ns);
writer.Close();
}
}

.

public class B
{
[XmlAttribute("c")]
public string C { get; set; }

public List<D> D { get; set; }
}

.

public class D
{
[XmlAttribute("e")]
public string E { get; set; }
}

.

A a = new A();
a.B = new B();
a.B.C = "c";
a.B.D = new List<D>();
D d = new D();
d.E = "e";
a.B.D.Add(d);
a.B.D.Add(d);
a.B.D.Add(d);
a.Save();

生成这样的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<A>
<B c="c">
<D>
<D e="e" />
<D e="e" />
<D e="e" />
</D>
</B>
</A>

有什么方法可以生成具有这种结构的 xml: ?

<?xml version="1.0" encoding="utf-8"?>
<A>
<B c="c">
<D e="e" />
<D e="e" />
<D e="e" />
</B>
</A>

最佳答案

B类装饰

[XmlElement("D")]
public List<D> D { get; set; }

关于c# - xml序列化——集合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7177524/

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