2016-03-20 84 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