阻塞问题反序列化XML到对象问题
问题描述:
我有阻塞问题 我有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; }
}
}
答
这似乎是期待/books/books/book
尝试,而不是:
[XmlElement("book")]
public Book[] Books { get; set; }
(no array/array-item)
答
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
或任何可序列化的集合像List
和List<T>
的基本上告诉串行器你想要数组的元素序列化为当前元素的子元素,即。由于您通过BooksCollection
类提供元素,因此您只需将数组序列化为BooksCollection
的子元素。
请不要在标题中复制“C#,.NET”等标签。将它们留在标签中。这就是标签的用途!此外,要格式化代码和/或XML,请在编辑器中选择它们并按下Control-K。 – 2010-06-14 08:26:35