2014-07-23 16 views
0

我解析XML來創建一個對象。我只是不確定如何將var lotConfig轉換爲LotCOnfig對象。XMLDescendants到對象

我曾嘗試:

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; 
     } 

回答

0

目前lotConfigIEnumerable<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(); 
+1

謝謝!它的工作原理,我會在5分鐘內接受答案 – user3774466