Deserialization Error: The XML element 'name' from namespace '' is already present in the current scope

前端 未结 9 1194
旧巷少年郎
旧巷少年郎 2020-12-18 07:43

This is my first time using XML Serialization and this is driving me absolutely nuts after 2 days of trying to troubleshoot this.

I get this error w

9条回答
  •  粉色の甜心
    2020-12-18 08:06

    Ok - I coded up an example. I took a look at the Facebook API, now here is a FULL working example. Try this:

    [XmlRoot("photos_getAlbums_response", Namespace="http://api.facebook.com/1.0/")]
    public class GetAlbumsResponse
    {
        public GetAlbumsResponse() 
        {    
        }
    
        [XmlElement("album")]
        public List Albums { get; set; }
    }
    
    public class Album
    {
        [XmlElement("aid")]
        public long Aid{get;set;}
    
        [XmlElement("cover_pid")]
        public long CoverPid{get;set;}
    
        [XmlElement("owner")]
        public long Owner{get;set;}
    
        [XmlElement("name")]
        public string Name{get;set;}
    
        [XmlElement("created")]
        public long Created{get;set;}
    
        [XmlElement("modified")]
        public long Modified{get;set;}
    
        [XmlElement("description")]
        public string Description{get;set;}
    
        [XmlElement("location")]
        public string Location{get;set;}
    
        [XmlElement("link")]
        public string Link{get;set;}
    
        [XmlElement("size")]
        public int Size{get;set;}
    
        [XmlElement("visible")]
        public string Visible{get;set;}
    
        public Album()
        {}
    }
    
    class XmlUtils
    {
        public static T DeserializeFromXml(string xml)
        {
            T result;
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextReader tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }
    }
    

    Now.. with an xml photos_getAlbums_response from the Facebook API,

    You can deserialize like this:

     GetAlbumsResponse response = XmlUtils.DeserializeFromXml(xmlResponseString);
    

提交回复
热议问题