【发布时间】:2009-11-05 21:45:09
【问题描述】:
尝试“解冻”已存储在 XML 文件中的序列化对象:
在 LinqToSQL 中,我可以(通过适当装饰的类)做这种事情:
[Table(Name="Plants")]
public class Plant
{
[Column(Name = "Id", IsPrimaryKey = true)]
public int Id { get; set; }
[Column(Name = "Genus")]
public string Genus { get; set; }
[Column(Name = "Species")]
public string Species { get; set; }
[Column(Name = "CommonName")]
public string CommonName { get; set; }
...
}
然后再这样做:
using (DataContext db = new DataContext(ConnectString))
{
plants = (
from d in db.GetTable<Plant>()
select d).ToList();
}
SQL 表中的数据用于填充植物对象的 List。
但是对于 LinqToXML,我似乎无法做到这一点,而是我必须这样做:
<!-- XML File -->
<Plants>
<Plant>
<Genus>Quercus</Genus>
<Species>alba</Species>
<CommonName>White Oak</CommonName>
</Plant>
...
</Plants>
// Class
[DataContract]
[XmlRoot("Plants")]
public class Plant
{
[DataMember]
public string Genus { get; set; }
[DataMember]
public string Species { get; set; }
[DataMember]
public string CommonName { get; set; }
...
}
// Code -- note: I already have the XML file in an XDocument called "doc"
IEnumerable<XElement> items = (from item in doc.Descendants("Plant")
where item.Element("Genus").Value.Equals("Quercus")
select item);
List<Plant> plants = new List<Plant>();
foreach (XElement item in items)
{
Plant a = new Plant();
a.Genus = item.Element("Genus").Value;
a.Species = item.Element("Species").Value;
XElement ex = item.Element("CommonName");
if ((null == ex) || ex.IsEmpty) { } else { a.Example = ex.Value; }
plants.Add(a);
}
鉴于我想让这个序列化/反序列化通用,有没有办法在不诉诸反射的情况下做到这一点?我可以使用 XmlSerializer,但这也涉及到大量的 MemoryStreams 和使用它们作为 XmlWriter 或 XmlReaders,而我想要的只是让我的类自动地进出 XML 文件。只是想知道我是否无法在这里连接点......
【问题讨论】:
标签: xml linq serialization