0

I'm trying to create a piece of XML that looks roughly like this:

<OuterTags>
  <MiddleTags>
    <Guests>
      <Adult />
      <Adult />
    </Guests>
  </MiddleTags>
</OuterTags>

However. Whenever I try to serialise this, I get:

<OuterTags>
  <MiddleTags>
    <Guests>
      <Adult xsi:nil="true" />
      <Adult xsi:nil="true" />
    </Guests>
  </MiddleTags>
</OuterTags>

...and I've proven that the xsi:nil="true" attributes are being rejected by my endpoint.

The code that I have generating the MiddleTags currently exists in two classes:

using System;
using System.Xml.Serialization;

namespace XmlRobot.DataTypes
{
  [Serializable]
  public class MiddleTags
  {
    [XmlArray("Guests")]
    [XmlArrayItem("Adult")]
    public Adult[] Adults { get; set; }
  }
}

...and...

using System;
using System.Xml.Serialization;

namespace XmlRobot.DataTypes
{
  [Serializable]
  public class Adult
  {
  }
}

I've found a question/answer here (Suppress xsi:nil but still show Empty Element when Serializing in .Net) that tells me how to make this tag work for a simple element (i.e. string/float), but I can't for the life of me make it work for my array!

Anyone got any pro advice?

Thanks, Tim

Community
  • 1
  • 1
Tim L
  • 141
  • 9

1 Answers1

1

If we have array with null references like this:

var middle = new MiddleTags();
middle.Adults = new Adult[2];

then during serialization:

var xs = new XmlSerializer(typeof(MiddleTags));
xs.Serialize(Console.Out, middle);

we will get:

<?xml version="1.0" encoding="cp866"?>
<MiddleTags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Guests>
    <Adult xsi:nil="true" />
    <Adult xsi:nil="true" />
  </Guests>
</MiddleTags>

However, if we fill out an array of instances of the class:

middle.Adults[0] = new Adult();
middle.Adults[1] = new Adult();

then we will get:

<?xml version="1.0" encoding="cp866"?>
<MiddleTags xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Guests>
    <Adult />
    <Adult />
  </Guests>
</MiddleTags>

Thus, before serialization, we can simply replace all null references to instances of the class:

for (int i = 0; i < middle.Adults.Length; i++)
    if (middle.Adults[i] == null)
        middle.Adults[i] = new Adult();

It is straightforward, but it works. How about it?

Of course, this may not be acceptable depending on the properties of the Adult class.

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49