LINQ to XML to POCO object

六月ゝ 毕业季﹏ 提交于 2019-12-05 21:01:14

Maybe try an explicit conversion

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

In case your POCO objects do not only have string properties, XElement and XAttribute provide a wide selection of conversion operators to other types, including nullables in case the element/attribute doesn't exist.

Example:

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"),
            // ...
        };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!