LINQ to XML for a POCO Object

I have an XML file that I want to include in the list of POCO objects.

I have the following working code for reading XML and creating objects from it. I just want to check that this is a good way to do this, and I don't miss any tricks. In particular with respect to the Linq subquery.

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

thank

+3
source share
2 answers

Maybe try 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 this:

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

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

Source: https://habr.com/ru/post/1760750/


All Articles