阻止问题将XML反序列化为对象问题

时间:2010-06-12 08:52:07

标签: c# .net xml

我遇到阻塞问题 我在某个网址下有XML文件

http://myserver/mywebApp/myXML.xml

在我在控制台应用程序中运行的以下代码中,bookcollection具有null Books字段:(


<books>
<book id="5352">
<date>1986-05-05</date>
<title>
Alice in chains
</title>
 </book>
<book id="4334">
<date>1986-05-05</date>
<title>
1000 ways to heaven
</title>
 </book>
<book id="1111">
<date>1986-05-05</date>
<title>
Kitchen and me
</title>
 </book>
</books>
XmlDocument doc = new XmlDocument(); 
doc.Load("http://myserver/mywebapp/myXML.xml");
BookCollection books = new BookCollection();

XmlNodeReader reader2 = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser2 = new XmlSerializer(books.GetType());
object obj = ser2.Deserialize(reader2);

BookCollection books2=   (BookCollection)obj; 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    [Serializable()]
      public class Book
        {
             [System.Xml.Serialization.XmlAttribute("id")]
            public string id { get; set; }

             [System.Xml.Serialization.XmlElement("date")]
            public string date { get; set; }

              [System.Xml.Serialization.XmlElement("title")]
            public string title { get; set; }


        }
}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [Serializable()]
    [System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)]
    public class BookCollection
    {
        [XmlArray("books")]
        [XmlArrayItem("book", typeof(Book))]
        public Book[] Books { get; set; }
    }
} 

2 个答案:

答案 0 :(得分:1)

似乎期待/books/books/book。请尝试改为:

    [XmlElement("book")]
    public Book[] Books { get; set; }

(没有数组/数组项)

答案 1 :(得分:1)

Marc 100%正确,通过更改您在Books数组上使用的属性,您可以正确地反序列化XML。我还想指出的一件事是你像这样构建你的XmlSerializer

BookCollection books = new (); 
XmlSerializer ser2 = new XmlSerializer(books.GetType()); 

新的BookCollection实例不需要获取该类型。您应该使用typeof

XmlSerializer ser2 = new XmlSerializer(typeof(BookCollection)); 

根据Marc的观点,完整的BookCollection类应该看起来像这样

[System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)]  
public class BookCollection  
{  
    [System.Xml.Serialization.XmlElement("book")]  
    public Book[] Books { get; set; }  
}

XmlElement属性放在Array或任何可序列化的集合(如ListList<T>)基本上告诉序列化程序您希望将数组的元素序列化为子级当前元素的元素即。因为您通过BooksCollection类提供元素,所以您只希望将数组序列化为BooksCollection的子元素。