Tim van Peterson
Tim van Peterson

Reputation: 238

C# XmlSerializer conditionally serialialize List<T> items

i need to serialize and deserialize XML with C# XmlSerializer (or is there something better?).

[XmlElement]
public virtual List<Map> Maps { get; set; }

public class Map
{
    [XmlAttribute("item")]
    public string Item { get; set; }

    [XmlAttribute("uri")]
    public string Uri { get; set; }
}

Maps = new List<Map>{
    new Map { Item="", Uri="" },
    new Map { Item="something", Uri="foo" },
    new Map { Item="", Uri="foo" },
}

The serializer should throw out every item with string.IsNullOrEmpty(map.Item) so that the resulting Xml only holds the map with "something". How can I achieve this without a big hassle?:

<Maps> <Map item="something" uri="foo" /> </Maps>

Upvotes: 2

Views: 81

Answers (2)

Habbi
Habbi

Reputation: 301

As far as I've understood, you want to filter your XML before you serialize it.

I suggest you use LINQ for this:

var filteredMaps = Maps.Where(map => !string.IsNullOrWhiteSpace(map.Item)).ToList();

Notice the .ToList() call at the end of the line. This is important, as your XmlSerializer is of type List<Map> I suppose. Put this line before you serialize your object and the result should look like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Map item="something" uri="foo" />
</ArrayOfMap>

Don't forget the using System.Linq;

Upvotes: 1

Zegar
Zegar

Reputation: 1015

Well you can try creating an XmlWriter that filters out all elements with an xsi:nil attribute or containing an empty string, and passes all other calls to the underlying standard XmlWriter to "clean up" serialized XML.

Upvotes: 0

Related Questions