开发者

C# Xml Serialization Inline Elements

Is there a way to force the XML serializer to add an element as inline rather than with the Value layout. I basically have just a giant list of structs and I'd like to add an inline element to each sub element that is enabled.

<main>
<item>
  <value>1</value>
  <name>Alphabet</name&开发者_高级运维gt;
</item>
...
</main>

I basically want to add:

<item Enabled="true">

if the element block is enabled. IS there a way to do this?


Yes, just mark the Enabled property with the XmlAttributeAttribute:

[XmlAttribute("Enabled")]
public bool Enabled { get; set; }

Documentation on the attributes that control xml serialization can be found on MSDN: http://msdn.microsoft.com/en-us/library/83y7df3e%28v=VS.100%29.aspx


XmlAttributeAttribute

The XmlAttributeAttribute attribute allows you to specify that a member should be serialized as an attribute and what that attribute should be named. Only simple data can be used as an attribute because an attribute can only represent a single value. Collapse

using System;
using System.Xml.Serialization;

namespace XmlEntities {
    [XmlRoot("XmlDocRoot")]
    public class RootClass {
        private int attribute_id;

        [XmlAttribute("id")]
        public int Id {
            get { return attribute_id; }
            set { attribute_id = value; }
        }
    }
}

This will serialize to something similar to this... Collapse

<XmlDocRoot id="1" />

more info check this answer on SO : How to add attributes for C# XML Serialization

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜