XML serialization of a non-nested repeating sequence

I need to serialize an array that has multiple nested values ​​i.e.

<MyArray> <Code>code1</Code> <Name>name associated with code 1</Name> <Code>code2</Code> <Name>name associated with code 2</Name> <Code>code3</Code> <Name>name associated with code 3</Name> <Code>code4</Code> <Name>name associated with code 4</Name> </MyArray> 

I tried various attributes in my array - for example,

 [XmlArray(ElementName="MyArray")] [XmlArrayItem(ElementName="")] public List<MyPair> MyPairs { get; set; } 

NB: the MyPair object contains 2 string properties (code and name):

but to no avail, I always get a containing element for each pair (which is usually better, but not what the circuit requires), and which I have no control over). Any help was greatly appreciated.

EDIT . This is part of a huge XML document, is it possible to use manual serialization of XElement for 1 part of it and XMLSerialization for the rest?

+4
source share
2 answers

Just to close it. I worked on the problem, I think it can be called a small hack, because I would like to avoid serializing the entire graph of the object manually. So:

  • Used XML serialization to serialize to a string
  • Manipulated string to remove additional nested elements
  • Designed the entire xml string for a single XElement (requires that this be correctly serialized as xml for WCF)
0
source

I see no other way than serializing your elements manually.

 XElement xElem = new XElement("MyArray", array.Select(m => new XElement[] { new XElement("Code", m.Code), new XElement("Name", m.Name) }) ); var xml = xElem.ToString(); 
+3
source

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


All Articles