Deserializing XML with namespace and multiple nested elements

前端 未结 2 1120
不思量自难忘°
不思量自难忘° 2020-12-20 20:25

I am trying to deserialize the following xml



  

        
相关标签:
2条回答
  • 2020-12-20 20:47

    The problem is that the namespace of myrootNS class is incorrect because it doesn't match the expected namespace in the XML.

    [XmlRoot("myroot", Namespace = "http://jeson.com/")]
    public class myrootNS
    {
        [XmlElement(Namespace = "")]
        public item[] item { get; set; }
    }
    

    Notice that the Namespace property value has a trailing /. This is my deserialize method:

    static T Deserialize<T>(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        XmlReaderSettings settings = new XmlReaderSettings();
        using (StringReader textReader = new StringReader(xml))
        {
            using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
            {
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-20 20:52

    As an alternative to the XmlRoot attribute, you can also use the alternative XmlRootAttribute constructor of XmlSerializer to override when the element name or namespace differ:

    var serializer = new XmlSerializer(typeof(myrootNS), 
                         new XmlRootAttribute                             
                         { 
                             ElementName = "myroot", 
                             Namespace = "http://jeson.com/" 
                         });
    
    0 讨论(0)
提交回复
热议问题