0

I am trying to serialize objects into xml. I have setup up

public class Foo<t>
{
    [XmlElement(ElementName ="test")]
    public <t> bar {
    get
    {
        var descriptor = TypeDescriptor.GetProperties(this.GetType())["bar"];

        var attrib =(XmlElementAttribute)descriptor.Attributes[typeof(XmlElementAttribute)];
        FieldInfo ElementName = attrib.GetType().GetProperty("ElementName")
        ElementName.SetValue(attrib, "success");
    }
    set{}
}

I want to change XmlElement.ElementName at run time but so far have been unsucessfull. According to this blog you should be able to do it. Also this SO post indicates that I am on the right track.

My Questions are Is what I want to do possible? How do I achieve this?

EDIT: I want the xml node to be called 'Success' instead of 'test'

Community
  • 1
  • 1
gh9
  • 10,169
  • 10
  • 63
  • 96

1 Answers1

2

The technique in that article only works for .NET components that depend on the TypeDescriptor system, which is a higher level abstraction than raw reflection. XmlSerializer is not one of those components as far as I know.

The closest you can come to "changing attributes at runtime" with respect to XmlSerializer is using XmlAttributeOverrides, but I forget how to use that because I've used it so infrequently. That only allows you to change them for the entire type though, not individual instances as you seem to want. This is partly because XmlSerializer actually compiles a serialization delegate internally that it uses over and over to serialize your type for reasons of performance.

Your best bet is probably to just implement the IXmlSerializable interface to customize the serialization for that particular class. XmlSerializer will honor that interface, and it will allow you to have 100% control over the XML by using XmlReader / XmlWriter. It is more difficult to have to manually write the serialization code, but you have much more control. And you only have to do it for the types in your graph that require custom handling. For an example of using IXmlSerializable see my answer to Override XML Serialization Method.

Community
  • 1
  • 1
luksan
  • 7,661
  • 3
  • 36
  • 38
  • Yes, XmlAttributeOverrides is the way to go. See e.g. [this SO question](http://stackoverflow.com/questions/2247086/how-to-override-xml-element-name-for-collection-elements-using-xmlattributeoverr). – Anton Tykhyy Jan 15 '14 at 21:29