2012-09-24 45 views
0

考慮下面的XML我想找到所有的成本值,並找到相關AltID的如何使用linq搜索同胞?

... 
    <Row ss:AutoFitHeight="0"> 
    <Cell ss:StyleID="s62"><Data ss:Type="String" AltID="1" ColumnHeader="AltName">Alternative 2</Data></Cell> 
    <Cell ss:StyleID="s62"><Data ss:Type="Number" ColumnHeader="Total">0.105468638</Data></Cell> 
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Cost">123</Data></Cell> 
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Risk">456</Data></Cell> 
    </Row> 
    <Row ss:AutoFitHeight="0"> 
    <Cell ss:StyleID="s62"><Data ss:Type="String" AltID="2" ColumnHeader="AltName">Alternative 3</Data></Cell> 
    <Cell ss:StyleID="s62"><Data ss:Type="Number" ColumnHeader="Total">1.7803949999999999</Data></Cell> 
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Cost">123</Data></Cell> 
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Risk">456</Data></Cell> 
    </Row> 
... 

我能找到的成本很容易(這是兩列在Excel XML數據表),但我需要找到一種方法來說,用這個給定的成本,去「上」一個級別,然後找到其ColumnHeader等於AltName,然後給我的AltID屬性的單元格。

Dim costs = From item In dg...<Table>...<Row>...<Cell>...<Data> Select item Where [email protected] = "Cost" 
    For Each i In costs 
     dim CostValue as Integer = i.value 
     dim AltID as Integer = ... 
    Next 
+0

爲什麼要使用linq?爲什麼不使用簡單的XPath查詢? –

回答

0

你不需要做三點來瀏覽每個元素。 Triple dot是.Descendents的簡寫。您可以將此簡化爲dg ...只要您不關心數據節點位於層次結構中的哪個位置即可。一旦你得到了你想要的節點,你可以使用Parent導航返回圖形,然後根據需要再次回退。這應該給你指定的節點AltID的屬性:

Dim costs = From item In dg...<Data> 
    Where [email protected] = "Cost" 
    select item.Parent.Parent...<Data>. 
       FirstOrDefault(Function(node) node.Attribute("ColumnHeader").Value = "AltName")[email protected] 

或者,您可以使用祖先,而不是.Parent.Parent來達到同樣的目的。見http://www.dbtalks.com/uploadfile/a7e1c8/linq-to-xml-axis-methods-part-1-ancestors-and-ancestorsands/