Xml Sequence deserialization with RestSharp

后端 未结 2 1281
面向向阳花
面向向阳花 2020-12-21 15:14

I have this xml feed from an API with a XML sequence.



    2002
             


        
2条回答
  •  忘掉有多难
    2020-12-21 16:01

    You can use the DotNetXmlDeserializer of RestSharp to make Microsoft's XmlSerializer do the actual deserialization. Define your MyResponse class as follows, using XML serialization attributes to specify element names and also special handling for the Cmd/Status alternating sequence of elements:

    [XmlRoot("Function")]
    public class MyResponse
    {
        [XmlIgnore]
        public List Settings { get; set; }
    
        /// 
        /// Proxy property to convert Settings to an alternating sequence of Cmd / Status elements.
        /// 
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [XmlAnyElement]
        public XElement[] Elements 
        {
            get
            {
                if (Settings == null)
                    return null;
                return Settings.SelectMany(s => new[] { new XElement("Cmd", s.Cmd), new XElement("Status", s.Status) }).ToArray();
            }
            set
            {
                if (value == null)
                    Settings = null;
                else
                    Settings = value.Where(e => e.Name == "Cmd").Zip(value.Where(e => e.Name == "Status"), (cmd, status) => new Setting { Cmd = (int)cmd, Status = (int)status }).ToList();
            }
        }
    }
    

    Then deserialize as follows:

            var serializer = new DotNetXmlDeserializer();
            var myResponse = serializer.Deserialize(response);
    

    Prototype fiddle.

提交回复
热议问题