抑制xsi:nil但在.Net中序列化时仍然显示空元素

时间:2009-11-10 18:23:07

标签: c# .net xml-serialization xml-nil

我有一个c#类,它有20多个字符串属性。我将其中的四分之一设置为实际值。我想序列化类并获得

的输出
<EmptyAttribute></EmptyAttribute>

属性

public string EmptyAttribute {get;set;}

我不希望输出为

<EmptyAttribute xsi:nil="true"></EmptyAttribute>

我正在使用以下课程

public class XmlTextWriterFull : XmlTextWriter
{
    public XmlTextWriterFull(string filename) : base(filename,Encoding.UTF8) { }

    public override void WriteEndElement()
    {
        base.WriteFullEndElement();
        base.WriteRaw(Environment.NewLine);
    }
}

这样我就可以获得完整的标签。我只是不知道如何摆脱xsi:nil。

2 个答案:

答案 0 :(得分:13)

XmlSerializer序列化属性而不添加xsi:nil="true"属性的方法如下所示:

[XmlRoot("MyClassWithNullableProp", Namespace="urn:myNamespace", IsNullable = false)]
public class MyClassWithNullableProp
{
    public MyClassWithNullableProp( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            new XmlQualifiedName(string.Empty, "urn:myNamespace") // Default Namespace
        });
    }

    [XmlElement("Property1", Namespace="urn:myNamespace", IsNullable = false)]
    public string Property1
    {
        get
        {
            // To make sure that no element is generated, even when the value of the
            // property is an empty string, return null.
            return string.IsNullOrEmpty(this._property1) ? null : this._property1;
        }
        set { this._property1 = value; }
    }
    private string _property1;

    // To do the same for value types, you need a "helper property, as demonstrated below.
    // First, the regular property.
    [XmlIgnore] // The serializer won't serialize this property properly.
    public int? MyNullableInt
    {
        get { return this._myNullableInt; }
        set { this._myNullableInt = value; }
    }
    private int? _myNullableInt;

    // And now the helper property that the serializer will use to serialize it.
    [XmlElement("MyNullableInt", Namespace="urn:myNamespace", IsNullable = false)]
    public string XmlMyNullableInt
    {
       get 
       {
            return this._myNullableInt.HasValue?
                this._myNullableInt.Value.ToString() : null;
       }
       set { this._myNullableInt = int.Parse(value); } // You should do more error checking...
    }

    // Now, a string property where you want an empty element to be displayed, but no
    // xsi:nil.
    [XmlElement("MyEmptyString", Namespace="urn:myNamespace", IsNullable = false)]
    public string MyEmptyString
    {
        get
        {
            return string.IsNullOrEmpty(this._myEmptyString)?
                string.Empty : this._myEmptyString;
        }
        set { this._myEmptyString = value; }
    }
    private string _myEmptyString;

    // Now, a value type property for which you want an empty tag, and not, say, 0, or
    // whatever default value the framework gives the type.
    [XmlIgnore]
    public float? MyEmptyNullableFloat
    {
        get { return this._myEmptyNullableFloat; }
        set { this._myEmptyNullableFloat = value; }
    }
    private float? _myEmptyNullableFloat;

    // The helper property for serialization.
    public string XmlMyEmptyNullableFloat
    {
        get
        {
            return this._myEmptyNullableFloat.HasValue ?
                this._myEmptyNullableFloat.Value.ToString() : string.Empty;
        }
        set
        {
            if (!string.IsNullOrEmpty(value))
                this._myEmptyNullableFloat = float.Parse(value);
        }
    }

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

现在,实例化这个类并将其序列化。

// I just wanted to show explicitly setting all the properties to null...
MyClassWithNullableProp myClass = new MyClassWithNullableProp( ) {
    Property1 = null,
    MyNullableInt = null,
    MyEmptyString = null,
    MyEmptyNullableFloat = null
};

// Serialize it.
// You'll need to setup some backing store for the text writer below...
// a file, memory stream, something...
XmlTextWriter writer = XmlTextWriter(...) // Instantiate a text writer.

XmlSerializer xs = new XmlSerializer(typeof(MyClassWithNullableProp),
    new XmlRootAttribute("MyClassWithNullableProp") { 
        Namespace="urn:myNamespace", 
        IsNullable = false
    }
);

xs.Serialize(writer, myClass, myClass.Namespaces);

检索XmlTextWriter的内容后,您应该输出以下内容:

<MyClassWithNullableProp>
    <MyEmptyString />
     <MyEmptyNullableFloat />
</MyClassWithNullableProp>

我希望这清楚地演示了内置的.NET Framework XmlSerializer如何用于将属性序列化为空元素,即使属性值为null(或者您不想要的其他值)连载)。此外,我已经展示了如何确保null属性根本不是序列化的。需要注意的一点是,如果您应用XmlElementAttribute并将该属性的IsNullable属性设置为true,那么当该属性为属性时,该属性将使用xsi:nil属性进行序列化null(除非在其他地方覆盖)。

答案 1 :(得分:-6)

我实际上能够解决这个问题。我知道它在某些方面有点黑客,但这就是我开始工作的方式

 System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(header.GetType());
        XmlTextWriterFull writer = new XmlTextWriterFull(FilePath);
        x.Serialize(writer, header);
        writer.Flush();
        writer.BaseStream.Dispose();
        string xml = File.ReadAllText(FilePath);
        xml = xml.Replace(" xsi:nil=\"true\"", "");
        File.WriteAllText(FilePath, xml);

希望这可以帮助其他人