2011-03-14 216 views
1

我一直在嘗試以下,但它返回意外的結果:動態LINQ查詢

Dim xd As XDocument = _ 
    <?xml version="1.0" encoding="utf-8"?> 
    <root> 
     <element> 
      <subelement id="1"> 
       <subsubelement id="1"/> 
       <subsubelement id="3"/> 
       <subsubelement id="1"/> 
      </subelement> 
      <subelement id="2"/> 
      <subelement id="3"/> 
     </element> 
     <element> 
      <subelement id="4"/> 
      <subelement id="3"/> 
      <subelement id="2"> 
       <subsubelement id="1"/> 
       <subsubelement id="1"/> 
       <subsubelement id="3"/> 
      </subelement> 
      <subelement id="5"/> 
     </element> 
    </root> 

    Dim haveSubelementId As Boolean = True 
    Dim haveSubSubelementId As Boolean = True 

    Dim results = From q In xd...<element> 
    If haveSubelementId Then 
     results = From q In results.<subelement> Where [email protected] = 1 
    End If 
    If haveSubSubelementId Then 
     results = From q In results.<subsubelement> Where [email protected] = 3 
    End If 

    results = results.Ancestors.<element> 

上述結果同時返回「元素」節點但是它應該只返回第一個where元素/子元素@ ID = 1/subsubelement @ id = 3

但是,如果results.Ancestors。被使用它返回正確的'子元素',如果該行不包含它返回一個'subsubelement'這也是正確的我不明白爲什麼當mvoing到'元素'它返回兩個(我意識到兩者都有一個子元素與id = 1,但我認爲每個進一步的查詢將過濾出以前的結果)任何人有任何建議?

回答

1

我可以讓它正常工作的唯一方法是通過執行以下操作:

Dim results = From q In xd...<element> 
    If haveSubelementId Then 
     results = From q In results.<subelement> Where [email protected] = 1 
    End If 
    If haveSubSubelementId Then 
     results = From q In results.<subsubelement> Where [email protected] = 3 
    End If 

    For Each xe As XElement In results 
     If haveSubSubelementId Then 
      xe = xe.Parent.Parent 
     If haveSubelementId Then 
      xe = xe.Parent 
     End If 
     Console.WriteLine(xe.ToString) 
    Next 

但它看起來有點笨拙,我曾希望,這將有可能從返回正確的元素集合搜索查詢。