4

I am using Automapper and classes with Xml serialization to generate an XML file.

In this method, it returns an IEnumerable to Automapper, which then writes out a series of <GenerationMethod>...</GenerationMethod> XML elements.

It does work, however, if it returns an empty IEnumerable, because no results were found, I am getting empty XML tags like this:

<GenerationMethod />

Is there a way to return NULL so that empty XML tags are not generated?

Here is the method. Thanks!

public static IEnumerable<GenerationMethod> GetGenerationMethod(this DungeonGrid monster)
{

    var customMonster = monster.Stats
            .Where(e => e.Stat.Category.IsActive);

    if (monster.MonsterType.DestructionMethod.StartsWith("TEST"))
    {
        yield return new GenerationMethod(monster.MonsterType.DestructionMethod);
    }

    foreach (Stat in customMonster)
    {
        if (DungeonLookupByStatId.ContainsKey(customMonster.MonsterType.Id))
            yield return DungeonLookupByStatId[customMonster.MonsterType.Id];
    }
}
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

1 Answers1

1

You final goal is to not include the GenerationMethod tag in the XML in case the IEnumerable is empty.

So I suggest you handle exactly that, not alter the method that returns the IEnumerable.
IEnumerable is like Schrödinger's cat. It has all the items and no items at all and only when you actually enumerate, you will know exactly what items it will yield.
So returning a null, instead of the IEnumerable would defy the purpose of the IEnumerable.

So, to answer your question, create your own xml serializer (Here is an answer on SO about how you can achieve that, or simply look it up. It should be pretty straight forward). All you need to do is to change the way the IEnumerable is written to the XML.
The logic should be pretty straight forward:

  1. Call the .ToList() extension method on your IEnumerable to enumerate it.
  2. If the list has items, create the tag and add the tags in the regular way.
  3. Do nothing if the list is empty.

I hope it gives you the direction you are looking for.

Alex Pshul
  • 694
  • 3
  • 11