gpt4 book ai didi

c# - Linq to XML 将元素添加到特定子树

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:39 24 4
gpt4 key购买 nike

我的 XML:

<Bank>
<Customer id="0">
<Accounts>
<Account id="0" />
<Account id="1" />
</Accounts>
</Customer>
<Customer id="1">
<Accounts>
<Account id="0" />
</Accounts>
</Customer>
<Customer id="2">
<Accounts>
<Account id="0" />
</Accounts>
</Customer>
</Bank>

我想添加新的 Account 元素来假设 ID 为 2 的客户。我知道如何添加我不知道如何指定客户的行(我在哪里写客户的 ID?)

我的 LINQ to XML 代码:

XDocument document = XDocument.Load("database.xml");
document.Element("Bank").Element("Customer").Element("Accounts").Add
(
new XElement
(
"Account", new XAttribute("id", "variable")
)
);
document.Save("database.xml");

感谢您的帮助。 XML 不是我的好 friend :(

最佳答案

您快完成了,您的代码将默认将元素添加到第一个 Customer。您需要在值为 2 的 Customers 集合中搜索属性 id -

document.Element("Bank").Elements("Customer")
.First(c => (int)c.Attribute("id") == 2).Element("Accounts").Add
(
new XElement
(
"Account", new XAttribute("id", "variable")
)
);

关于c# - Linq to XML 将元素添加到特定子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com