简体   繁体   中英

How to serialize some Array/Class as Attribute to XML C#?

I am trying to find a way how to serialize some array or class/struct as Attribute of element not like inner element/elements.

I want to make in such way:

<SomeElement Margin="0,0,0,0" />

Not like:

<Margin>
   <Left/>
   <Top/>
   <Right/>
   <Bottom/>
</Margin>

Unfortunately XMLSerializer doesnt provide a solution to your problem. However, you can add your own implementation to get the desired output.

public class SomeElement
{
    [XmlAttribute(AttributeName = "Margin")]
    public string MarginString { get; set; }

    [XmlIgnore]
    public List<int> MarginList
    {
        get
        {
            return MarginString.Split(',').Select(x => Convert.ToInt32(x.Trim())).ToList();
        }
        set
        {
            MarginString = String.Join(",", value);
        }
    }
}


var somelement = new SomeElement { MarginList = new List<int> { 0, 0, 0, 0 } };
var serializer = new XmlSerializer(somelement.GetType());
serializer.Serialize(Console.Out, somelement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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