2011-01-12 71 views
1

我已經從一個傳統的應用中的一些不規範的XML:嵌套的LINQ to XML

<PODRoot> 
<RowData> 
<PODItem>Item243</PODItem> 
<StoragePath>PODItem66</StoragePath> 
<ID>-13</ID> 
<PODType>3</PODType> 
<Description>Transfer to MPF PODs</Description> 
<MemoString></MemoString> 
<PODLink> 
    <LinkType>1</LinkType> 
    <Location>HTMLPage1.htm</Location> 
    <Description>HTMLPage1.htm</Description> 
</PODLink> 
<PODLink> 
    <LinkType>2</LinkType> 
    <Location>HTMLPage2.htm</Location> 
    <Description>HTMLPage2.htm</Description> 
</PODLink> 

...

,並做在SL4應用程序下面,裏面也沒有對於PODLink節點工作:

  List<PODNode> Nodes = (List<PODNode>)from podNode in doc.Descendants("RowData") 
        select new PODNode 
        { 
         ItemName = podNode.Element("PODItem").Value, 
         StoragePath = podNode.Element("StoragePath").Value, 
         ID = Convert.ToInt32(podNode.Element("ID").Value), 
         PODNodeType = (NodeType)Convert.ToInt32(podNode.Element("PODType").Value), 
         Description = podNode.Element("Description").Value, 
         Comment = podNode.Element("MemoString").Value, 
         //Links = (List<PODLink>)from podLink in podNode.Descendants("PODLink") 
         //      select new PODLink 
         //      { 
         //       LinkType = podLink.Element("LinkType").Value, 
         //       Location = podLink.Element("Location").Value, 
         //       Description = podLink.Element("Description").Value 

         //      }; 
        }; 

下面是相關類:

public class PODNode 
{ 
    public NodeType PODNodeType; 
    public string ItemName = string.Empty; 
    public int ID; 
    public string StoragePath = string.Empty; 
    public string Description = string.Empty; 
    public string Comment = string.Empty; 
    public List<PODNode> Nodes; 
    public List<PODLink> Links; 
} 

任何想法如何,是否有可能,我可以讓註釋掉的部分工作?

回答

0

更改爲使用XMLReader。多一點的代碼,但它工作正常。

2

試試這個:

List<PODNode> Nodes = (from podNode in doc.Descendants("RowData") 
     select new PODNode 
     { 
      ItemName = podNode.Element("PODItem").Value, 
      StoragePath = podNode.Element("StoragePath").Value, 
      ID = Convert.ToInt32(podNode.Element("ID").Value), 
      PODNodeType = (NodeType)Convert.ToInt32(podNode.Element("PODType").Value), 
      Description = podNode.Element("Description").Value, 
      Comment = podNode.Element("MemoString").Value, 
      Links = (from podLink in podNode.Descendants("PODLink") 
       select new PODLink 
       { 
        LinkType = podLink.Element("LinkType").Value, 
        Location = podLink.Element("Location").Value, 
        Description = podLink.Element("Description").Value 

       }).ToList() 
     }).ToList(); 

我認爲你的問題是,內部查詢是不是List<PODLink>,它可能的IEnumerable<PODLink>IQueryable<PODLink>類型,你可以不投給List<PODLink>的。但你可以執行ToList()方法,它應該可以解決你的問題。

更新:使代碼看起來更好,並刪除所有的演員。 更新:修正了這個例子中的兩個錯誤,可能還有更多,因爲我沒有編譯它。

+0

大多數情況下,該代碼會產生一堆錯誤,無效的表達式。謝謝你的迴應。 – 2011-01-12 16:14:49