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

前端 未结 9 1219
旧巷少年郎
旧巷少年郎 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:31

    (08 Feb) First, treating xml as a string (for reading) isn't going to cause errors.

    The problem is the namespace (the xmlns without the xsi); this wasn't in the earlier xml, so I couldn't include it... basically, you need to tell the serializer about it:

    [Serializable, XmlRoot("photos_GetAlbums_response",
        Namespace="http://api.example.com/1.0/")]
    public class GetAlbumsResponse { /* code as before */ }
    
    [Serializable, XmlType(Namespace="http://api.example.com/1.0/")]
    public class Album { /* code as before */ }
    

    On this occasion, a constant for the namespace would make sense (since you are re-using it).

    If the xml you are showing is accurate, then the links are still corrupt, though... but maybe this is just copy/paste (i.e. don't apply this change until you know it errors...): you need & (not &). Suggest some "Replace"... at the crudest level:

    string fixedXml = xml.Replace("&", "&");
    

    (although something more precise might be better - perhaps a regex)

    Note that with the different data I also had to make some of the data strings (rather than long):

    [XmlElement("aid")]
    public string AlbumID { get; set; }
    
    [XmlElement("cover_pid")]
    public string CoverPhotoID { get; set; }
    
    [XmlElement("owner")]
    public string Owner { get; set; }
    

    With these changes (and mostly my original code) it works.

    Of course, by this point you should be thinking "I wish I'd used xsd".

提交回复
热议问题