C#学习教程:LinqtoXML向特定子树添加元素我不知道如何指定客户(我在哪里写客户的ID?)我的LINQtoXML代码:XDocumentdocument=XDocument.Load("database.xml");document.Element("Bank").Element("Customer").Element("Accounts").Add(newXElement("Account",newXAttribute("id","variable")));文档.保存("数据库.xml");感谢您的帮助。XML不是我的朋友:(你快到了,默认情况下,你的代码将向第一个Customer添加元素。你需要在Customers集合中搜索值为2的属性id-document.Element("Bank").Elements("Customer").First(c=>(int)c.Attribute("id")==2).Element("Accounts").Add(newXElement("Account",newXAttribute("id","variable")));我知道如何添加行我不知道如何指定客户(我在哪里写客户的ID?)你需要先找到ID正确的Customer元素。例如:varcustomer=document.Root.Elements("Customer").Single(x=>(int)x.Attribute("id")==id);customer.Element("Accounts").Add(newXElement("Account",newXAttribute("id","variable")));请注意,如果不存在具有正确ID的单个Customer元素,则Single调用将失败。如果您想创建一个新的客户端,您将需要做更多的工作——但可能是在另一个电话上。以上就是C#学习教程:LinqtoXMLaddingelementstoaspecificsubtree的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——varcust=xDoc.Descendants("Customer").First(c=>c.Attribute("id").Value=="2");cust.Element("Accounts").Add(newXElement("Account",newXAttribute("id","3")));本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
