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
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"),
// ...
};
来源:https://stackoverflow.com/questions/3531565/linq-to-xml-to-poco-object