8

別のリスト(バリアントのある製品)内にリストがあります。親リストに属性を設定したいのですが(とだけidname

必要な出力

<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>

4

1 に答える 1

12

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; }
}
于 2012-12-11T01:34:41.197 に答える