2012-11-12 48 views
2

我正在嘗試一天來完成這項工作。我想更新使用LINQ在我的XML貨幣屬性的XML使用LINQ to XML更新子樹中的XML屬性

我的XML看起來是這樣的:

<Bank> 
    <Customer id="0"> 
    <FName>Adam</FName> 
    <LName>Kruz</LName> 
    <Accounts> 
     <Account id="0" money="1500" /> 
     <Account id="1" money="6500" /> 
     <Account id="2" money="0" /> 
    </Accounts> 
    </Customer> 
    <Customer id="1"> 
    <FName>Benny</FName> 
    <LName>Thoman</LName> 
    <Accounts> 
     <Account id="0" money="3200" /> 
    </Accounts> 
    </Customer> 
</Bank> 

從來就BEEM這個代碼,但沒有成功

XDocument document = XDocument.Load("database.xml"); 

     XElement root = document.Root; 

     root.Elements("Customer") 
      .Where(e => e.Attribute("id").Value.Equals(customerID.ToString())).Select(e => e.Descendants("Account") 
       .Where(f => f.Attribute("id").Value.Equals(this.id.ToString())).Select(f => f.Attribute("id")).First().SetValue(money.ToString())); 


     document.Save("database.xml"); 

嘗試我收到一個錯誤: 方法'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)'的類型參數不能從用法中推斷出來。嘗試明確指定類型參數。

請告訴我,我怎麼在一個元素(賬戶)感謝的子樹(帳戶)編輯屬性很多:(

回答

0

試試這個:

var query = 
    from c in document.Root.Elements("Customer") 
    where c.Attribute("id").Value == customerID.ToString() 
    from a in c.Element("Accounts").Elements("Account") 
    where a.Attribute("id").Value == this.id.ToString() 
    select a; 

query 
    .First() 
    .Attribute("money") 
    .SetValue(money.ToString()); 
+0

這一項工作完美的感謝! – Safiron