代码之家  ›  专栏  ›  技术社区  ›  user3774466

对象的XMLDescendants

  •  0
  • user3774466  · 技术社区  · 11 年前

    我正在解析XML以创建对象。我只是不确定如何将var-lotConfig转换为lotConfig对象。

    我尝试过:

    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;
            }
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   har07    11 年前

    目前 lotConfig 属于类型 IEnumerable<LotConfig> ,你需要打电话 .FirstOrDefault() 在LINQ结束时,使其返回单个 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();