c# - 使用 LINQ to XML 更新子树中的 XML 属性

标签 c# xml linq

我花了一天的时间来完成这项工作。我想使用 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>

我一直在尝试这段代码,但没有成功

 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)”的类型参数。尝试明确指定类型参数。

请告诉我如何编辑元素(帐户)的子树(帐户)中的属性,非常感谢:(

最佳答案

试试这个:

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());

关于c# - 使用 LINQ to XML 更新子树中的 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342172/

相关文章:

c# - 在 Entity Framework 中不同

c# - XMLSerializer反序列化——数组元素顺序

c# - if (val1 == val2) 与 if(val1 != val2)

java - 如何在 Java 中获取 SoapUI 请求和响应 XML

C# 仅从节点文本中转义非法 xml 字符

java - 通过 XML 中的特定标记名称查找元素是否存在

c# - 在 lucene 搜索之前,我如何通过外键过滤我的数据?

c# - 如何将谓词生成器与 linq2sql 和 OR 运算符一起使用

c# - 使用 htmlagility pack 替换 src 值

c# - ModelState.isvalid 返回 false?