gpt4 book ai didi

c# - 具有属性的列表的 XML 序列化

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:45 26 4
gpt4 key购买 nike

我在另一个列表中有一个列表(具有变体的产品)。我希望父列表在其上设置属性(只是一个 id 和一个 name)。

期望的输出

<embellishments>
<type id="1" name="bar bar foo">
<row>
<id>1</id>
<name>foo bar</name>
<cost>10</cost>
</row>
</type>
</embellishments>

当前代码

[XmlRoot( ElementName = "embellishments", IsNullable = false )]
public class EmbellishmentGroup
{
[XmlArray(ElementName="type")]
[XmlArrayItem("row", Type=typeof(Product))]
public List<Product> List { get; set; }

public EmbellishmentGroup() {
List = new List<Product>();
List.Add( new Product() { Id = 1, Name = "foo bar", Cost = 10m } );
}
}

public class Product
{
[XmlElement( "id" )]
public int Id { get; set; }

[XmlElement( "name" )]
public string Name { get; set; }

[XmlElement( "cost" )]
public decimal Cost { get; set; }
}

当前输出

<embellishments>
<type>
<row>
<id>1</id>
<name>foo bar</name>
<cost>10</cost>
</row>
</type>
</embellishments>

最佳答案

您需要创建另一个代表 type 元素的类。然后你可以为它的属性添加属性,像这样:

[XmlRoot(ElementName = "embellishments", IsNullable = false)]
public class EmbellishmentGroup
{
[XmlElement("type")]
public MyType Type { get; set; }

public EmbellishmentGroup()
{
Type = new MyType();
}
}

public class MyType
{
[XmlAttribute("id")]
public int Id { get; set; }

[XmlAttribute("name")]
public string Name { get; set; }

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

public MyType()
{
Id = 1;
Name = "bar bar foo";
List = new List<Product>();
Product p = new Product();
p.Id = 1;
p.Name = "foo bar";
p.Cost = 10m;
List.Add(p);
}
}

public class Product
{
[XmlElement( "id" )]
public int Id { get; set; }

[XmlElement( "name" )]
public string Name { get; set; }

[XmlElement( "cost" )]
public decimal Cost { get; set; }
}

关于c# - 具有属性的列表的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13811991/

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