簡體   English   中英

如何使用 Xml 屬性序列化 XML 和節點的 collections

[英]How to serialize XML with collections of nodes using Xml Attributes

我正在嘗試使用XmlSerializer並使用其屬性來序列化 Xml 。 我的問題是我沒有得到EVENT項目的數據。 我不完全了解如何使用屬性( XmlRootXmlElement - 我應該使用XmlArray嗎?)來處理EVENTSCOLLECTIONEVENT之間的組合,我得到了帶有 0 個項目的EventsCollection 我寧願擺脫EventsCollection class - 它存在只是因為我不知道如何使用組合。 這是我的 XML:

<MSGDATA>
    <EVENTSCOLLECTION>
        <EVENT>
            <Id>1</Id>
            <EventNumber>100</EventNumber>
        </EVENT>
        <EVENT>
            <Id>2</Id>
            <EventNumber>200</EventNumber>
        </EVENT>
        <EVENT>
            <Id>3</Id>
            <EventNumber>300</EventNumber>
        </EVENT>
    </EVENTSCOLLECTION>
</MSGDATA>

這是數據結構:

[XmlRoot(ElementName="EVENT")]
public class EventItem
{
    [XmlElement("Id")]
    public int ID {get; set;}
    
    [XmlElement("EventNumber")]
    public int EventNumber {get; set;}
}

//I would get rid of it if I could find a way
[XmlRoot(ElementName="EVENTSCOLLECTION")]
public class EventsCollection
{
    private List<EventItem> eventItems
    public List<EventItem> EventItems
    {
        get
        {
            if (eventItems == null)
            {
                eventItems = new List<EventItem>();
            }
            return eventItems;
        }
        set
        {
            eventItems = value;
        }
    }
}

[XmlRoot(ElementName="MSGDATA")]
public class EventMsgData
{
    [XmlElement("EVENTSCOLLECTION")]
    //I would replace this propery with a property with a type of List<EventItem> if I would know how to combine it with the XML attributes 
    private EventsCollection events;
    public EventsCollection Events { get; set;  }
}

這就是我嘗試序列化它的方式:

XmlSerializer xmls = new XmlSerialized(typeof(EventMsgData));
EventMsgData result = (EventMsgData)xmls.Deserialize(new StringReader(<text of MSGDATA xml node>))

我通過進行這些更改來解決它:

  1. 我刪除了 EventsCollection class - 它不是必需的。

  2. 我使用了以下屬性:

    [XmlArray("EVENTSCOLLECTION")]

    [XmlArrayItem("事件")]

在EventMsgData class中,如下圖:

[XmlArray("EVENTSCOLLECTION")]
[XmlArrayItem("EVENT")]
public List<EventItem> EventItems

暫無
暫無

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

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