2016-03-20 86 views
1

我需要使用XML文件填充類。使用LINQ查詢填充類

<Ship> 
    <Name>Base Ship</Name> 
    <Owner>PG</Owner> 
    <Aim> 
     <Type>base</Type> 
     <Value>10</Value> 
     <Last>-1</Last> 
    </Aim> 
    <Aim> 
     <Type>cannon</Type> 
     <Value>10</Value> 
     <Last>2</Last> 
    </Aim> 
    <Dodge> 
     <Type>base</Type> 
     <Value>10</Value> 
     <Last>-1</Last> 
    </Dodge> 
    <EmPower> 
     <Type>base</Type> 
     <Value>10</Value> 
     <Last>-1</Last> 
    </EmPower> 
</Ship> 

我的問題是如何來填充Dictionary<string, CustomStruct>

這是struct

public struct Stat 
{ 
    public int StatValue { get; set; } 
    public int StatLast { get; set; } 

    public Stat(int statValue, int statLast) 
    { 
     StatValue = statValue; 
     StatLast = statLast; 
    } 
} 

我的LINQ查詢看起來是這樣的:

string loadDataPath = Application.persistentDataPath + "/saveData.xml"; 
XDocument loadData = XDocument.Load(loadDataPath); 

var query = from item in loadData.Elements("Ship") 
      select new Ship() 
      { 
       Name = (string) item.Element("Name"), 
       Owner = (string) item.Element("Owner"), 
       Aim = item.Elements("Aim") // <-- Here lies the problem. 
       // ... 
      }; 

對於每個目標XElements我需要使用t填充Aim字典他下面的方法:

Aim TKey = XML Type 
Aim TValue.StatValue = XML Value 
Aim TValue.StatLast = XML Last 
+0

如果你看看我的更新答案,你就會知道爲什麼'struct'沒有工作。 –

回答

1

使用ToDictionary()擴展方法來實現你想要的:

Aim = item.Elements("Aim").ToDictionary(x => (string)x.Element("Type"), x => new Stat(int.Parse((string)x.Element("Value")), int.Parse((string)x.Element("Last")))) 

此外,我不得不改變structclassStat,以使其發揮作用。

如果你想使用struct你需要稍作修改:

public struct Stat 
{ 
    public int StatValue { get; set; } 
    public int StatLast { get; set; } 
    public Stat(int statValue, int statLast) : this() 
    { 
     StatValue = statValue; 
     StatLast = statLast; 
    } 
} 

this answer得到這個。

+0

on item.Elements(「Aim」): 無法將實例參數類型'System.Collections.Generic.IEnumerable '轉換爲'System.Collections.Generic.IEnumerable ' – smark91

+0

@ smark91嘗試它現在 –

+0

@FᴀʀʜᴀɴAɴᴀᴍ只是FYI,在LINQ to XML中,正確的方法是使用cast而不是'Parse'。一般來說,對於XML來說,最好使用'XmlConvert'方法,否則你必須總是將'CultureInfo.InvariantInfo'傳遞給每一個'Parse'調用,你可以很容易地忘記(像你一樣:) –

1

這裏是正確的LINQ to XML語法:

Aim = item.Elements("Aim").ToDictionary(
    e => (string)e.Element("Type"), 
    e => new Stat((int)e.Element("Value"), (int)e.Element("Last"))) 
+0

這兩個作品,所以也謝謝你! – smark91