How to override xml element name for collection elements using XmlAttributeOverrides?

I have a basic object model of an object that is serialized with System.Xml.XmlSerialization material. I need to use the XmlAttributeOverrides function to set the xml element names for a set of child elements.

public class Foo{
  public List Bars {get; set; }
}

public class Bar {
  public string Widget {get; set; }
}

using a standard XML serializer, it will look like

 <Foo>
  <Bars>
    <Bar>...</Bar>
  </Bars>
 </Foo>

I need to use XmlOverrideAttributes to say:

 <Foo>
  <Bars>
    <SomethingElse>...</SomethingElse>
  </Bars>
 </Foo>

but I can’t get him to rename the children in the collection ... I can rename the set itself ... I can rename the root ... not sure what I am doing wrong.

here is the code i have right now:

XmlAttributeOverrides xOver = new XmlAttributeOverrides();

var bars = new XmlElementAttribute("SomethingElse", typeof(Bar));
var elementNames = new XmlAttributes();
elementNames.XmlElements.Add(bars);
xOver.Add(typeof(List), "Bars", elementNames);

StringBuilder stringBuilder = new StringBuilder();
StringWriter writer = new StringWriter(stringBuilder);
XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
serializer.Serialize(writer, someFooInstance);

string xml = stringBuilder.ToString();

but that doesn't change the name of the element at all ... what am I doing wrong?

thank

+3
2

, [XmlArray] [XmlArrayItem] ( , ):

using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Foo {
    public List<Bar> Bars { get; set; }
}  
public class Bar {
    public string Widget { get; set; }
}
static class Program {
    static void Main() {
        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
        xOver.Add(typeof(Foo), "Bars", new XmlAttributes {
            XmlArray = new XmlArrayAttribute("Bars"),
            XmlArrayItems = {
                new XmlArrayItemAttribute("SomethingElse", typeof(Bar))
            }
        });
        XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
        using (var writer = new StringWriter()) {
            Foo foo = new Foo { Bars = new List<Bar> {
                new Bar { Widget = "widget"}
            }};
            serializer.Serialize(writer, foo);
            string xml = writer.ToString();
        }            
    }
}
+8

,

- , :

public class Foo
{
    [XmlArrayItem(ElementName = "SomethingElse")]
    public List<Bar> Bars { get; set; }
}
+2

Source: https://habr.com/ru/post/1732405/


All Articles