XMLDescendants to Object
本文关键字:Object to XMLDescendants | 更新日期: 2023-09-27 18:14:13
我正在解析XML以创建对象。我只是不确定如何将var lotConfig转换为lotConfig对象。
I have try:
var lotConfig = (LotConfig) xml.Descendants("LOT_CONFIGURATON").Select(
和
return lotConfig as LotConfig
但是到目前为止都没有成功。
public LotConfig GetLotConfigData(FileInfo lotFile)
{
var xml = XElement.Load(lotFile.FullName);
var lotConfig = xml.Descendants("LOT_CONFIGURATON").Select(
lot => new LotConfig
{
LotNumber = (string) lot.Element("LOT_NUMBER").Value,
LotPartDescription = lot.Element("PART_DESCRIPTION").Value,
LotDate = lot.Element("LOT_DATE").Value,
ComponentList = lot.Descendants("ASSY_COMPONENT").Select(ac => new LotComponent
{
PartNumber = ac.Descendants("COMPONENT_PART_NUMBER").FirstOrDefault().Value,
ArtworkNumber = ac.Descendants("ARTWORK_NUMBER").FirstOrDefault().Value,
RefDesignator = ac.Descendants("REFERENCE_DESIGNATOR").FirstOrDefault().Value
}).ToList()
});
return lotConfig as LotConfig;
}
目前lotConfig
是IEnumerable<LotConfig>
类型,您需要在LINQ结束时调用.FirstOrDefault()
以使其返回单个LotConfig
类型:
var lotConfig = xml.Descendants("LOT_CONFIGURATON")
.Select(
lot => new LotConfig
{
LotNumber = (string) lot.Element("LOT_NUMBER").Value,
LotPartDescription = lot.Element("PART_DESCRIPTION").Value,
LotDate = lot.Element("LOT_DATE").Value,
ComponentList = lot.Descendants("ASSY_COMPONENT").Select(ac => new LotComponent
{
PartNumber = ac.Descendants("COMPONENT_PART_NUMBER").FirstOrDefault().Value,
ArtworkNumber = ac.Descendants("ARTWORK_NUMBER").FirstOrDefault().Value,
RefDesignator = ac.Descendants("REFERENCE_DESIGNATOR").FirstOrDefault().Value
}).ToList()
})
.FirstOrDefault();