XML 反序列化:从 xmlString 到复杂 class

XML Deserialization : from xmlString to complex class

这是 xml 我从数据库中得到的:

> <Library>
>     <Header>
>         <HeaderID>01</HeaderID>
>     </Header>
>     <Books>
>         <Book>
>             <Name>Book1</Name>
>             <Category>Fiction</Category>
>             <Authors>2</Authors>
>         </Book>
>         <Book>
>             <Name>Book2</Name>
>             <Category>Non - Fiction</Category>
>             <Authors>1</Authors>
>         </Book>
>      </Books>
>      <Authors>
>           <Author>
>               <Name>Author1ForBook1</Name>
>           </Author>
>           <Author>
>               <Name>Author2ForBook1</Name>
>           </Author>
>           <Author>
>               <Name>Author1ForBook2</Name>
>           </Author>
>       </Authors> 
></Library>

这是我的 class:

public class Library
{
   public Header header{get; set;}
   public List<Book> books{get;set;}
   public List<Author> authors{get;set;}
}

public class Header
{
   int ID{get;set;}
}

public class Book
{
  string Name{get; set;}
  string Category{get; set;}
  string Fiction{get; set;}
}

public class Author
{
  string Name{get;set;}
}

我想要做的是,将从数据库中获取的 xml 字符串反序列化为 class 对象 - Library。目前我正在使用以下代码,但出现错误:

String xData = RequestXml;
XmlSerializer x = new XmlSerializer(typeof(Library));
Library myTest = (Library)x.Deserialize(new StringReader(xData));

我得到的错误是:

XML 文档 (1, 2) 中存在错误。

查看这篇文章。您可以自动生成所需的一切,因此您不必手动编写代码并犯错误。

http://blogs.msdn.com/b/yojoshi/archive/2011/05/14/xml-serialization-and-deserialization-entity-classes-with-xsd-exe.aspx

关于您在问题中的评论。

basically I cannot get the value for Library.Header.ID. How can I achieve it?

因为它是 Library.Header.HeaderID 而不是 Library.Header.ID.. 你的 属性 被命名为 ID..

在您的属性上使用和定义数据注释来映射元素

 using System.Xml.Serialization;

 public class Header
 {
   [XmlElement(DataType = "integer", ElementName = "HeaderID")]
   int ID{get;set;}
 }

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute(v=vs.110).aspx

我的新 class 看起来像这样,而且很有魅力:

 [XmlRoot("Library")]
    public class Library
    {
         [XmlElement("Header")]
        public Header header { get; set; }
         [XmlElement("Book")]
        public List<Book> books { get; set; }
         [XmlElement("Author")]
        public List<Author> authors { get; set; }
    }


    public class Header
    {

        public int HeaderID { get; set; }
    }

    public class Book
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public string Fiction { get; set; }
    }

    public class Author
    {
       public  string Name { get; set; }
    }