【问题标题】:How to mark up your C# object to Deserialize this XML如何标记您的 C# 对象以反序列化此 XML
【发布时间】:2012-03-27 00:52:06
【问题描述】:

我不敢相信这有多复杂......

我有以下 XML...

<Library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://mynamespace.com/books">
  <Rows>
    <Row>
      <Author><Name>Stephen King</Name></Author>
    </Row>  
   </Rows>
</Library>

我希望反序列化的 C# 对象读起来像... Library.Books[0].Author

我已经尝试过一百万种不同的 XML 属性标记组合来反序列化,例如...

[XmlRootAttribute("Library", Namespace = "http://mynamespace.com/books", IsNullable = false)]
public class Library
{
    [XmlElement("Rows")]
    public List<Book> Books { get; set; }
}

[XmlRoot("Row")]
public class Book
{
    public Author Author { get; set; }
}

[XmlRoot("Author")]
public class Author
{
    public string Name { get; set; }
}

...当我尝试反序列化时,我不断地将“作者”对象设为空。它几乎成功了...我确实在 Books 属性中获得了带有一个 Book 项目的 ArrayList。但对于我的一生,我无法得到作者。

任何建议/帮助将不胜感激!

【问题讨论】:

  • 公平地说,这不是我的目标……它是你的。 This 可能会对您有所帮助。

标签: c# xml-deserialization xml-attribute


【解决方案1】:

试试

public class Library
{
    [XmlArray("Rows")]
    [XmlArrayItem("Row")]
    public List<Book> Books { get; set; }
}

【讨论】:

  • 非常好。 Book 和 Author 此时不需要任何额外的说明符。集合的重新序列化也有效。我会接受这个答案。
【解决方案2】:

如果你想用'手写'来写,你可以使用这些扩展方法:http://searisen.com/xmllib/extensions.wiki

public class Library
{
    XElement self;
    public Library() { self = XElement.Load("libraryFile.xml"); }
    public Book[] Books 
    { 
        get 
        { 
            return _Books ?? 
                (_Books = self.GetEnumerable("Rows/Row", x => new Book(x)).ToArray()); 
        } 
    }
    Book[] _Books ;
}

public class Book
{
    XElement self;
    public Book(XElement xbook) { self = xbook; }
    public Author Author 
    { 
        get { return _Author ??
            (_Author = new Author(self.GetElement("Author")); }
    Author _Author;
}

public class Author
{
    XElement self;
    public Author(XElement xauthor) { self = xauthor; }
    public string Name 
    { 
        get { return self.Get("Name", string.Empty); }
        set { self.Set("Name", value, false); }
    }
}

制作它需要更多样板代码,以便您可以添加新书,但您的帖子是关于阅读(反序列化)的,所以我没有添加。

【讨论】:

  • 有趣的方法,可能对我有所帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多