LINQ to XML to POCO object

自作多情 提交于 2019-12-07 13:46:50

问题


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

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


回答1:


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



回答2:


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"),
            // ...
        };


来源:https://stackoverflow.com/questions/3531565/linq-to-xml-to-poco-object

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