gpt4 book ai didi

c# - 如何使用 linq to XML 添加/插入条件节点到 XML

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

我生成了一个这样的 xml 文件:

 XElement employees =
new XElement("Work",
new XElement("record",
new XElement("Name", textBox1.Text),
new XElement("Phone", "206-555-0144"),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)),
new XElement("record",
new XElement("Name", "22222"),
new XElement("Phone", "353245345"),
new XElement("Address",
new XElement("Street1", "sdfain St"),
new XElement("City", "asdf Island"),
new XElement("State", "QLD"),
new XElement("Postal", "54322")
)),
new XElement("record",
new XElement("Name", "Peter"),
new XElement("Phone", "1234"),
new XElement("Address",
new XElement("Street1", "sd St"),
new XElement("City", "cbr"),
new XElement("State", "act"),
new XElement("Postal", "2600")
)
)
);

稍后我希望根据条件(where name="peter")在父节点“record”下添加新的子节点,如下所示:

empFile.Elements().Where(r => (string)r.Element("Name") == "Peter")
.Add(new XElement("record",
new XElement("Mobile", "3253425"),
new XElement("Work", 999999)
));

我怎样才能做到这一点?

最佳答案

除了 Tim 建议使用 Where 后接 SingleFirst 之外,值得一提的是,这些方法的重载已经取谓词。例如:

empFile.Elements()
.Single(r => (string) r.Element("Name") == "Peter")
.Add(...);

关于c# - 如何使用 linq to XML 添加/插入条件节点到 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3544897/

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