简体   繁体   中英

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>

好吧,您可以尝试创建XmlWriter,该过滤器过滤掉所有带有xsi:nil属性或包含空字符串的元素,并将所有其他调用传递给基础标准XmlWriter,以“清理”序列化的XML。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM