【问题标题】:How to serialize XML with collections of nodes using Xml Attributes如何使用 Xml 属性序列化带有节点集合的 XML
【发布时间】:2022-01-01 02:55:15
【问题描述】:

我正在尝试使用 XmlSerializer 并使用其属性来序列化 Xml。 我的问题是我没有得到 EVENT 项目的数据。 我不完全了解如何使用属性(XmlRootXmlElement 来处理 EVENTSCOLLECTIONEVENT 之间的组合strong> - 我应该使用 XmlArray 吗?) 我得到了 0 个项目的 EventsCollection。我宁愿摆脱 EventsCollection 类 - 它只是因为我不知道如何使用组合。 这是我的 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>))

【问题讨论】:

    标签: c# xml-serialization xmlserializer xml-attribute


    【解决方案1】:

    我通过这些更改解决了这个问题:

    1. 我删除了 EventsCollection 类 - 它不是必需的。

    2. 我已经使用了属性:

      [XmlArray("EVENTSCOLLECTION")]

      [XmlArrayItem("EVENT")]

    在EventMsgData类中,如下图:

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

    【讨论】:

      猜你喜欢
      • 2010-12-28
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2015-07-18
      • 1970-01-01
      相关资源
      最近更新 更多