Can I configure the DataContractSerializer to not create optional (i.e. Nullable<> and List<>) elements in output XML?

后端 未结 2 512
天命终不由人
天命终不由人 2021-02-07 15:11

I am using the new .NET 3.0 DataContractSerializer. I have both Nullable<> and List<> objects I am going to serialize. Example:

[DataContract(Na         


        
相关标签:
2条回答
  • 2021-02-07 15:32

    Mark the field with

       [DataMember(EmitDefaultValue=false)]
    

    That will work for at the least the nullable value type case. For the List case you may need to defer creation of the list until it is needed, or else null the member if it is empty before serialization.

    0 讨论(0)
  • 2021-02-07 15:47

    I really needed the same thing, but applied globally to lots of fields in generated RIA classes. I'm not sure if this XML is acceptable to DataConstract for deserializing. But it is readable, which suites my purposes...

        public override string ToString()
        {
            var doc = XDocument.Parse(this.ToXML());
            WalkElement(doc.Root);
            return doc.ToString( SaveOptions.None );
        }
        void WalkElement(XElement e)
        {
            var n = e.GetNamespaceOfPrefix("i");
            if (n != null)
            {
                var a = e.Attribute(n + "nil");
                if (a != null && a.Value.ToLower() == "true")
                    e.Remove();
            }
            foreach (XElement child in e.Elements().ToList())
                WalkElement(child);
        }
    
    0 讨论(0)
提交回复
热议问题