簡體   English   中英

禁止使用xsi:nil,但在.Net中進行序列化時仍顯示空元素

[英]Suppress xsi:nil but still show Empty Element when Serializing in .Net

我有一個具有20多個字符串屬性的ac#類。 我將其中的四分之一設置為實際值。 我想序列化該類並獲得輸出

<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。

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 ,則當該屬性為null (除非在其他地方被覆蓋),該屬性將使用xsi:nil屬性進行序列化。

我實際上能夠弄清楚這一點。 我知道它在某些方面有點hack,但這就是我如何使其工作

 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);

希望這可以幫助別人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM