Serialize XML same tag twice
Use an array:
public class Test{ [XmlElement("HeaderText")] public string[] HeaderText { get; set; }}
and then:
var doc = new Test{ HeaderText = new[] { "AAA", "BBB" }};var xml = new XmlSerializer(typeof(Test));using (var fs = new FileStream("test.xml", FileMode.Create)){ xml.Serialize(fs, doc);}
Also works with List<string>
.
UPDATE:
With complex objects you define a model:
public class Header{ public string Tag { get; set; }}
and then you have a collection of this model:
public class Test{ [XmlElement("HeaderText")] public Header[] HeaderText { get; set; }}
and then you serialize:
var doc = new Test{ HeaderText = new[] { new Header { Tag = "AAA" }, new Header { Tag = "BBB" } }};var xml = new XmlSerializer(typeof(Test));using (var fs = new FileStream("test.xml", FileMode.Create)){ xml.Serialize(fs, doc);}
You could tell the serializer to ignore your current properties, and add a new one for the purpose of serialization:
public class Test{ [XmlIgnore] public String Header1 { get; set; } [XmlIgnore] public String Header2 { get; set; } [XmlElement("HeaderText")] public String[] HeaderText { get{ return new[]{Header1,Header2}; } set{ if(value.Length == 2) { Header1 = value[0]; Header2 = value[1];} } }}
Live example: http://rextester.com/YVEF64085