LINQ到XML来POCO对象 [英] LINQ to XML to POCO object

查看:77
本文介绍了LINQ到XML来POCO对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了我想要的转向POCO对象的列表的XML文件。

I've got an XML file that I want to turn in to a list of POCO objects.

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

I have the following working code to read the XML and create objects from it. I just want to check this is a good way to do this and I'm not missing any tricks. In particular with regards to the nested Linq query.

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<ColumnMap>()               
        };
List<ImportDefinition> def = q.ToList<ImportDefinition>();



感谢

Thanks

推荐答案

也许尝试显式转换

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()
        }; 
    }
}



然后使用它像这样:

Then use it like so:

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

这篇关于LINQ到XML来POCO对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆