繁体   English   中英

具有属性的列表的XML序列化

[英]XML serialization of a list with attributes

我在另一个列表(具有变体的产品)中有一个列表。 我希望父列表上设置属性(只是一个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元素的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; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM