3

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>
</item>
...
</main>

I basically want to add:

<item Enabled="true">

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

Liz
  • 251
  • 2
  • 9

2 Answers2

2

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

rsbarro
  • 27,021
  • 9
  • 71
  • 75
1

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

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263