Home  /  Questions  /  Question



88   96.5
May 16, 2011


How can I generate xml elements or attributes from a custom collection?

 Hi:

I have a custom collection and items have two properties. 
I want to serialize one property to an xmlelement and another property to an xmlattribute. How can I do this? 

Thanks.
Best Regards.



50   50
May 17, 2011
To accomplish your goal add attributes to the properties in your collection. When the XML Serializer writes the XML it will create the requested node type.

Here's a sample in C#
using System.Xml.Serialization;

namespace SampleApp
{
    [XmlRoot("MyCollection")]
    class CustomCollection
    {
        [XmlElement("myElement")]
        public string MyElementProperty { get; set; }

        [XmlAttribute("myAttribute")]
        public string MyAttributeProperty { get; set; }
    }
}
Hope it helps,

Steve

 
 1 comment
 
Hi Steve, thanks for your answer but if you derived CustomCollection class from CollectionBase, it ignores element and attributes,doesnt serialize,how can i do. --- Volkan Genç  May 17, 2011

60   95.3
Jun 01, 2011

Give the [Serializable] attribute to appropriate property such a way you can serialize it by selective members.

using System.Xml.Serialization;

namespace SampleApp
{
    [Serializable][XmlRoot("MyCollection")]
    class CustomCollection
    {
        [XmlElement("myElement")]
        public string MyElementProperty { get; set; }

        [XmlAttribute("myAttribute")]
        public string MyAttributeProperty { get; set; }
    }
}


Thanks
Rajesh

 2 comments
 
Hi Rajesh , Can you send me a working example... --- Volkan Genç  Jun 01, 2011
 
You can try this... using System.Xml.Serialization; namespace SampleApp { [Serializable][XmlRoot("MyCollection")] class CustomCollection { [XmlElement("myElement")] public string MyElementProperty { get; set; } [XmlAttribute("myAttribute")] public string MyAttributeProperty { get; set; } } } --- Rajesh Shanmugam  Jun 23, 2011

0   0
May 28, 2018
Wow! I have one of the most trending game that you loves to play online most of the kids loves to play fireboy and watergirl online game without any download and login the goal of the game is to collect the gems and run more to achieve the gems and avoid to pass through the red blue and green lake.