将xml存储在对象中 [英] store xml in object
本文介绍了将xml存储在对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比如说,我有这样的 xml 文件:
say, i have such xml file:
<?xml version="1.0"?>
<catalog>
<title>My book catalog</title>
<link>http://example.com/catalog</link>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
最后需要获取对象,我可以使用如下:
in the end it's needed to get object, which i can use as follows:
xml.title //must return "My book catalog"
xml.link //must return "http://example.com/catalog"
xml.book[0] //is an object with following properties:
//author, title, genre etc...
//i.e., xml.book[0].author must return Gambardella, Matthew
希望没有类似的问题,如果有,抱歉,我没有找到.另外,如果有关于此特定情况的任何文档,请指出它,因为我找不到它.有很多关于以各种方式解析 xml 的文档,但没有关于这种情况的信息.
hope that there was no similar question and sorry if there any, my bad, that i didn't found. also, if there any documentation for this, particular case, please point to it, because i just couldn't find it. there was plenty of documentation about xml parsing in various ways, but no info on this case.
提前致谢.
推荐答案
这里是使用 这些扩展方法:
[DebuggerDisplay("{Title}")]
public class Catalog
{
XElement self;
public Catalog(XElement catalog) { self = catalog; }
public string Title { get { return self.Get("title", string.Empty); } }
public Uri Link { get { return self.Get<Uri>("link", null); } }
public Book[] Books
{
get { return _Books ?? (_Books = self.GetEnumerable("book", x => new Book(x)).ToArray()); }
}
Book[] _Books;
[DebuggerDisplay("{Title} by {Author}")]
public class Book
{
XElement self;
public Book(XElement book) { self = book; }
public string Id { get { return self.Get("id", string.Empty); } }
public string Author { get { return self.Get("author", string.Empty); } }
public string Title { get { return self.Get("title", string.Empty); } }
public string Genre { get { return self.Get("genre", string.Empty); } }
public decimal Price { get { return self.Get<decimal>("price", 0); } }
public DateTime PublishDate { get { return self.Get("publish_date", DateTime.MinValue); } }
public string Description { get { return self.Get("description", string.Empty); } }
}
}
并使用它:
Catalog catalog = new Catalog(XElement.Load(file)); // or .Parse(string)
这篇关于将xml存储在对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文