gpt4 book ai didi

C# Xml 序列化 : Serialize Class properties as attributes to the parent class

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

[Serializable]
public class XX
{
[XmlAttribute("name")]
public string name{get;set;}
}

[Serializable]
[XmlRoot("tree")]
public class XY
{
public XX Name{get;set;}

[XmlAttribute("surname")]
public Surname{get;set;}
}

您好,我正在尝试将类似上述这些类的内容序列化为 XML。我的问题是 XX 类的属性应该序列化为 XY 类序列化的属性,而不是 XmlElement。任何人都知道它是否可行?在这里澄清的是应该产生的 xml 文件的示例:

<tree name="Jack" surname="Thompson">
</tree>

我不想要这个:

<tree surname="Thompson">
<name>Jack</name>
</tree>

最佳答案

您可能应该调整您的类结构以反射(reflect)您想要的 xml。如果“name”只是元素“tree”的属性,那么理想情况下,字符串“name”应该是类“XY”的属性,而类“XX”根本不存在。

但是,如果您真的需要这些类像现在这样存在,那么我会建议创建第三个类作为代理项,它的结构与您的 xml 匹配,并在类 XY 中创建一个方法,它将自己翻译成你的新类(class)。然后序列化新类而不是 XY 和 XX。

关于C# Xml 序列化 : Serialize Class properties as attributes to the parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10212001/

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