C#XML数组序列化 - 跳过“空”字符串值

时间:2009-08-18 03:31:23

标签: c# .net xml-serialization

我想在C#中的xml序列化期间跳过XML文件中的空元素创建。

前:

ArrayElements elm = new ArrayElements 
{ Items =new string[]  "Item1", " ", "Item2", " ", " ", "Items" } };

在序列化期间,它应该跳过空字符串。

这是我的班级:

[Serializable]
public class ArrayElements
{
    [XmlElement(IsNullable=false)]
    public string[] Items { get; set; }
}

2 个答案:

答案 0 :(得分:8)

您可以使用代理属性来执行此操作。

namespace Cheeso.Xml.Samples.Arrays
{
    static class Extensions
    {
        private static XmlSerializerNamespaces _ns;

        static Extensions()
        {
            // to suppress unused default namespace entries in the root elt
            _ns = new XmlSerializerNamespaces();
            _ns.Add( "", "" );
        }

        public static string SerializeToString(this XmlSerializer s, object o)
        {
            var builder = new System.Text.StringBuilder();
            var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };

            using ( var writer = System.Xml.XmlWriter.Create(builder, settings))
            {
                s.Serialize(writer, o, _ns);
            }
            return builder.ToString();
        }
    }

    [XmlType("ArrayOfString")]
    public class MyContainer
    {
        [XmlIgnore]
        public String[] a;

        // surrogate property
        [XmlElement("string")]
        public String[] A
        {
            get
            {
                List<String> _proxy = new List<String>();
                foreach (var s in a)
                {
                    if (!String.IsNullOrEmpty(s))
                        _proxy.Add(s);
                }
                return _proxy.ToArray();
            }
            set
            {
                a = value;
            }
        }
    }

    class StringArrayOnlyNonEmptyItems
    {
        static void Main(string[] args)
        {
            try 
            {
                Console.WriteLine("\nRegular Serialization of an array of strings with some empty elements:");
                String[] x = { "AAA", "BBB",  "",  "DDD",  "", "FFF" };
                XmlSerializer s1 = new XmlSerializer(typeof(String[]));
                string s = s1.SerializeToString(x);
                Console.WriteLine(s);

                Console.WriteLine("\nSerialization of an array of strings with some empty elements, via a Container:");
                MyContainer c = new MyContainer();
                c.a = x;
                XmlSerializer s2 = new XmlSerializer(typeof(MyContainer));
                s = s2.SerializeToString(c);
                Console.WriteLine(s);
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("uncaught exception:\n{0}", exc1);
            }
        }
    }
}

答案 1 :(得分:2)

你确定这是你想要的吗?一个缺点是,当你反序列化时,你将无法找回空字符串,因为反序列化器无法知道它们。通常在反序列化时,您希望返回一个与您最初序列化的实例完全相同的实例。

如果 是你想要的,那么你必须调整你的对象以适应序列化过程。正如Cheeso所说,替代财产是一个很好的解决方案。

另外,为了清楚起见,我是否正确地说你有一个对象ArrayElements,它有一个属性Items,这是一个string的数组?