Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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

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 when the deserialization kicks in:

The XML element 'name' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

The error happens on this line in my code:

Album album = (Album)serializer.Deserialize(reader);

I not sure why. There is no dup "name" node so I just don't get it. This is an XML doc received from an HttpWebResponse from a 3rd party REST API.

Here's the complete code:

My Album Class (the type I'm Deserializing to):

    public class Album
    {
        #region Constructors

        public Album() 
        { 

        }

        #endregion

        #region ElementConstants

        public static class ElementConstants
        {
            public const string aID = "aid";
            public const string Owner = "owner";
            public const string AlbumName = "name";
            public const string CoverPhotoID = "cover_pid";
            public const string CreateDate = "created";
            public const string LastModifiedDate = "modified";
            public const string Description = "description";
            public const string Location = "location";
            public const string AlbumURL = "link";
            public const string Size = "size";
            public const string Visible = "visible";
        }

        #endregion ElementConstants

        #region Public Properties

        [XmlArray(ElementName = "photos_GetAlbums_response")]
        [XmlArrayItem( "album" )]
        public Album[] Albums { get; set; }

        [XmlElement (ElementName = ElementConstants.AlbumName, DataType = "string")]
        public string AlbumID { get; set; }

        [XmlElement(ElementName = ElementConstants.aID, DataType = "int")]
        public Int32 CoverPhotoID { get; set; }

        [XmlElement(ElementName = ElementConstants.Owner, DataType = "string")]
        public string Owner { get; set; }

        [XmlElement(ElementName = ElementConstants.AlbumName, DataType = "string")]
        public string AlbumName { get; set; }

        [XmlElement(ElementName = ElementConstants.aID, DataType = "DateTime")]
        public DateTime CreateDate { get; set; }

        [XmlElement(ElementName = ElementConstants.LastModifiedDate, DataType = "DateTime")]
        public DateTime LastModifiedDate { get; set; }

        [XmlElement(ElementName = ElementConstants.Description, DataType = "string")]
        public string Description { get; set; }

        [XmlElement(ElementName = ElementConstants.Location, DataType = "string")]
        public string Location { get; set; }

        [XmlElement(ElementName = ElementConstants.AlbumURL, DataType = "string")]
        public string Link { get; set; }

        [XmlElement(ElementName = ElementConstants.Size, DataType = "size")]
        public string Size { get; set; }

        [XmlElement(ElementName = ElementConstants.Visible, DataType = "string")]
        public string Visible { get; set; }

        #endregion
    }

My Serializer Class:

    public class Serializer
    {
        public static Album CreateAlbumFromXMLDoc(XmlDocument doc)
        {
            // Create an instance of a serializer
            var serializer = new XmlSerializer(typeof(Album));
            var reader = new StringReader(doc.ToString());

            // Deserialize the Xml Object and cast to type Album
            Album album = (Album)serializer.Deserialize(reader);

            return album;
        }
    }

The XML that I am trying to Deserialized (copied from the Xml Doc object being passed into the CreateAlbumFromXMLDoc method when debugging in VS):

<?xml version="1.0" encoding="UTF-8"?>
<photos_GetAlbums_response xsi:schemaLocation="http://api.example.com/1.0/ http://api.example.com/1.0/xxx.xsd" list="true">
<album>
 <aid>3231990241086938677</aid>
 <cover_pid>7031990241087042549</cover_pid>
 <owner>1337262814</owner>
 <name>LA</name>
 <created>1233469624</created>
 <modified>1233469942</modified>
 <description>trip to LA</description>
 <location>CA</location>
 <link>http://www.example.com/album.php?aid=7333&id=1337262814</link>
 <size>48</size>
 <visible>friends</visible>
 </album>
<album>
 <aid>7031990241086936240</aid>
 <cover_pid>7031990241087005994</cover_pid>
 <owner>1337262814</owner>
 <name>Wall Photos</name>
 <created>1230437805</created>
 <modified>1233460690</modified>
 <description/>
 <location/>
 <link>http://www.example.com/album.php?aid=3296&id=1337262814</link>
 <size>34</size>
 <visible>everyone</visible>
 </album>
<album>
 <aid>7031990241086937544</aid>
 <cover_pid>7031990241087026027</cover_pid>
 <owner>1337262814</owner>
 <name>Mobile Uploads</name>
 <created>1231984989</created>
 <modified>1233460349</modified>
 <description/>
 <location/>
 <link>http://www.example.com/album.php?aid=6300&id=1337262814</link>
 <size>3</size>
 <visible>friends</visible>
 </album>
<album>
 <aid>7031990241086936188</aid>
 <cover_pid>7031990241087005114</cover_pid>
 <owner>1337262814</owner>
 <name>Christmas 2008</name>
 <created>1230361978</created>
 <modified>1230362306</modified>
 <description>My Album</description>
 <location/>
 <link>http://www.example.com/album.php?aid=5234&id=1337262814</link>
 <size>50</size>
 <visible>friends</visible>
 </album>
<album>
 <aid>7031990241086935881</aid>
 <cover_pid>7031990241087001093</cover_pid>
 <owner>1637262814</owner>
 <name>Hock</name>
 <created>1229889219</created>
 <modified>1229889235</modified>
 <description>Misc Pics</description>
 <location/>
 <link>http://www.example.com/album.php?aid=4937&id=1637262814</link>
 <size>1</size>
 <visible>friends-of-friends</visible>
 </album>
<album>
 <aid>7031990241086935541</aid>
 <cover_pid>7031990241086996817</cover_pid>
 <owner>1637262814</owner>
 <name>Test Album 2 (for work)</name>
 <created>1229460455</created>
 <modified>1229460475</modified>
 <description>this is a test album</description>
 <location/>
 <link>http://www.example.com/album.php?aid=4547&id=1637262814</link>
 <size>1</size>
 <visible>everyone</visible>
 </album>
<album>
 <aid>7031990241086935537</aid>
 <cover_pid>7031990241086996795</cover_pid>
 <owner>1637262814</owner>
 <name>Test Album (for work)</name>
 <created>1229459168</created>
 <modified>1229459185</modified>
 <description>Testing for work</description>
 <location/>
 <link>http://www.example.com/album.php?aid=4493&id=1637262814</link>
 <size>1</size>
 <visible>friends</visible>
 </album>
 </photos_GetAlbums_response>

A side note: Just for the hell of it, I paste that XML into XML Notepad 2007, it tells me:

Your XML document contains no xml-stylesheet processing instruction. To provide an XSLT transform, add the following to the top of your file and edit the href attribute accordingly:

I don't think that really means it's malformed or anything but just something to note.

So..

My ultimate goal is to get pass this damn error obviously and get an array of albums back using my code above once I can get past the error. I also want to make sure my code is correct in trying to retrieve that arrray back of albums using my Album[] property in my Album class or anything else I might be missing here. I think it's pretty close and should work but it's not.


Follow-up. I've been pulling my hair out since then.

Here's the latest. I did not use some things for now (from Marc) like the Enum, etc. I might change that later. I also pulled out the datetime stuff as it just looked wierd and I did not get errors on that anway without...at least yet. The main problem now is still my damn XML.

It's still appearing to have problems with the format I guess? Unless it's covering up another problem, no clue. This is driving me fing crazy.

I now get this error when the deserialization kicks in:

Data at the root level is invalid. Line 1, position 1.

The error happens on this line in my code: GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(reader);

How I get the response into an XmL doc:

public static XmlDocument GetResponseXmlDocument(HttpWebResponse response)
        {
            Stream dataStream = null; // stream from WebResponse
            XmlDocument doc = new XmlDocument();

            if (doc == null)
            {
                throw new NullReferenceException("The web reponse was null");
            }

            // Get the response stream so we can read the body of the response
            dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access
            StreamReader reader = new StreamReader(dataStream);

            // Load response into string variable so that we can then load into an XML doc
            string responseString = reader.ReadToEnd();

            // Create an XML document & load it with the response data
            doc.LoadXml(responseString);

            // Final XML document that represents the response
            return doc;
        }

My Album Class & Root Level Class (thanks to help from Marc..I get it now):

namespace xxx.Entities
{

    [Serializable, XmlRoot("photos_GetAlbums_response")]
    public class GetAlbumsResponse
    {
        [XmlElement("album")]
        public List<Album> Albums { get; set; }

        [XmlAttribute("list")]
        public bool IsList { get; set; }
    }

    public class Album
    {
        #region Constructors

        public Album()
        {

        }

        #endregion

        #region ElementConstants

        /// <summary>
        /// Constants Class to eliminate use of Magic Strings (hard coded strings)
        /// </summary>
        public static class ElementConstants
        {
            public const string aID = "aid";
            public const string Owner = "owner";
            public const string AlbumName = "name";
            public const string CoverPhotoID = "cover_pid";
            public const string CreateDate = "created";
            public const string LastModifiedDate = "modified";
            public const 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Personally, I wouldn't use constants here - they make it hard to spot errors (and since you probably aren't re-using them, don't add much). For example:

    [XmlElement (ElementName = ElementConstants.AlbumName, DataType = "string")]
    public string AlbumID { get; set; }
...
    [XmlElement(ElementName = ElementConstants.AlbumName, DataType = "string")]
    public string AlbumName { get; set; }

Looks suspect to me...

An easier approach is to write the xml you want to a file (foo.xml, say) and use:

xsd foo.xml
xsd foo.xsd /classes

Then look at foo.cs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...