0

I created a .NET class for XML serialization

[Serializable()]
[XmlRoot("documents")]
public class BdfXmlData
{
    [XmlElement("document")]
    public List<XmlElement> Documents { get; set; }

    public BdfXmlData()
    {
        Documents = new List<XmlElement>();
    }
}

When I try to serialize an object, I get with this tree:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfXmlElement xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <XmlElement>
    <documents>
      <document>
               ...
      <document>
    <documents>
  </XmlElement>
</ArrayOfXmlElement>

How can I have the following three?

<?xml version="1.0" encoding="utf-8"?>
<documents>
  <document>
    ...
  <document>
<documents>

Thanks in advance.

The code to serialize my class is the following:

public static string GetSerializedObject<T>(T t)
{
    using (MemoryStream stream = new MemoryStream())
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stream, t);
        stream.Position = 0;
        using (StreamReader reader = new StreamReader(stream))
        return reader.ReadToEnd();
    }
}
Termininja
  • 6,620
  • 12
  • 48
  • 49

3 Answers3

0

I think you can at least simplify your xml-code:

<ArrayOfdocuments xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <documents>
    <document>
               ...
    <document>
  <documents>
</ArrayOfdocuments>

The "XmlElement" element can be left out.

rbr94
  • 2,227
  • 3
  • 23
  • 39
0

Surely you are serialising an array of BdfXmlData

in pseudo code

BdfXmlData[] dataInArray = new [] {new BdfXmlData()};
GetSerializedObject(dataInArray)

would produce what you have whereas,

in pseudo code..

BdfXmlData data = new BdfXmlData();
GetSerializedObject(data)

should give you what you want!

Phil Blackburn
  • 1,047
  • 1
  • 8
  • 13
0

Exact, I serialise the Documents collection :

SerializationHelper.GetSerializedObject(xmlRootData.Documents);

In fact, I receive some XmlElement with this tree :

<document>
           ...
<document>

and I add these elements to my List "Documents".

xmlRootData.Documents.Add(xmlData);

When I serialise my final object (BdfXmlData), the xml contains 2 documents tags and 2 document tags

string xmlData = SerializationHelper.GetSerializedObject(xmlRootData);

<documents xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <document>
    <documents>
      <document>
      </document>
    <documents>
  </document>
</documents>