2010-06-12 90 views
2

我有阻塞問題 我有XML文件在某些​​URL 阻塞問題反序列化XML到對象問題

http://myserver/mywebApp/myXML.xml

在下面的代碼,我在控制檯應用程序運行,bookcollection都是空書籍領域:(


<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; } 
    } 
} 
+0

請不要在標題中複製「C#,.NET」等標籤。將它們留在標籤中。這就是標籤的用途!此外,要格式化代碼和/或XML,請在編輯器中選擇它們並按下Control-K。 – 2010-06-14 08:26:35

回答

1

這似乎是期待/books/books/book嘗試,而不是:

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

(no array/array-item)

1

Marc是100%正確的,通過更改您在Books數組上使用的屬性,您可以正確地反序列化XML。有一件事我也想指出的是,當你建立你的XmlSerializer這樣

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

它不是neccesary新BookCollection的實例來獲得類型。你還是使用typeof

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

而且按照馬克的點完全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的子元素。