LINQ to XML to POCO对象

我有一个XML文件,我想将其转换为POCO对象列表。

我有以下工作代码来读取XML并从中创建对象。 我只是想检查这是一个很好的方法来做到这一点,我不会错过任何技巧。 特别是关于嵌套的Linq查询。

XDocument xmlDoc = XDocument.Load(path); var q = from file in xmlDoc.Descendants("File") select new ImportDefinition() { Name = file.Attribute("Name").Value, TypeName = file.Attribute("TypeName").Value, ColumnMappings = ( from map in file.Descendants("ColumnMap") select new ColumnMap() { DatabaseColumn = new Column() { Name = map.Element("DatabaseColumn").Attribute("Name").Value } } ).ToList() }; List def = q.ToList(); 

谢谢

也许尝试一下明确的转换

 public class ColumnMap { public static explicit operator ColumnMap(XElement xElem) { return new ColumnMap() { DatabaseColumn = new Column() { Name = xElem.Element("DatabaseColumn").Attribute("Name").Value } }; } } public class ImportDefinition { public static explicit operator ImportDefinition(XElement xElem) { return new ImportDefinition() { Name = (string)xElem.Attribute("Name"), TypeName = (string)xElem.Attribute("TypeName"), Size = (int)xElem.Attribute("Size"), LastModified = (DateTime?)xElem.Attribute("LastModified"), ColumnMappings = xElem.Descendants("ColumnMap").Select(xelem => (ColumnMap)xelem).ToList() }; } } 

然后像这样使用它:

 XDocument xmlDoc = XDocument.Load(path); List importDefinitions = xmlDoc.Descendants("File").Select(xElem => (ImportDefinition)xElem).ToList() 

如果您的POCO对象不仅具有字符串属性,则XElement和XAttribute会为其他类型提供多种转换运算符 ,包括在元素/属性不存在的情况下为nullables。

例:

 XDocument xmlDoc = XDocument.Load(path); var q = from file in xmlDoc.Descendants("File") select new ImportDefinition() { Name = (string)file.Attribute("Name"), TypeName = (string)file.Attribute("TypeName"), Size = (int)file.Attribute("Size"), LastModified = (DateTime?)file.Attribute("LastModified"), // ... };