2014-01-09 42 views
0
<Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2"> 
....</Shape> 
<Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5"> 
....</Shape> 

我必須返回每個ID值的主值。 我怎樣才能實現它通過使用LINQ到XMl。如何使用linq獲取xml代碼的屬性值

回答

0

你真的不存在於您的XML文檔的樣子,所以我認爲這是如下:

<Shapes> 
    <Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2"> 
    </Shape> 
    <Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5"> 
    </Shape> 
</Shapes> 

你可以簡單地得到Master屬性值都不同ID這樣的:

var xDoc = XDocument.Load("Input.xml"); 

var masters = xDoc.Root 
        .Elements("Shape") 
        .ToDictionary(
        x => (int)x.Attribute("ID"), 
        x => (int)x.Attribute("Master") 
       ); 

masters將是Dictionary<int, int>其中關鍵是您的ID和值是相應的Master屬性值。