gpt4 book ai didi

c# - 如何在 C# 中修改 XML 文件?

转载 作者:数据小太阳 更新时间:2023-10-29 02:30:23 25 4
gpt4 key购买 nike

<Customers>
<Customer1>
<Name>Bobby</Name>
<Age>21</Age>
<Address>Panjim</Address>
</Customer1>
<Customer2>
<Name>Peter</Name>
<Age>32</Age>
<Address>Panjim</Address>
</Customer2>
<Customer4>
<Name>Joel</Name>
<Age>32</Age>
<Address>Mapusa</Address>
</Customer4>
</Customers>

所以问题是我想删除一个特定的元素,当我删除第一个元素,即 customer1 时,我想更新其他元素。我的意思是我想创建 customer3、customer2 和 customer2、customer1。谁能帮我实现这个目标?

最佳答案

关于:

class Program {
static void Main(string[ ] args) {
XDocument doc = XDocument.Load("D:\\file.xml"); //example file
doc.Root.SwitchAndRemove("Customer1");
doc.Save("D:\\file.xml");
}
}

public static class Utilities {
public static void SwitchAndRemove(this XElement customers, XName name) {
var x = customers.Descendants().Where(e => e.Name == name).Select((element, index) => new { element, index }).Single();

int count = 0;
XElement temp = x.element;
foreach (XElement el in customers.Nodes()) {
if (count == x.index + 1) {
temp.RemoveAll();
temp.Add(el.Descendants().ToArray());
temp = el;
}
else
count++;
}

temp.Remove();
}
}

通过将您的 xml 作为输入,输出如下:

<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer1>
<Name>Peter</Name>
<Age>32</Age>
<Address>Panjim</Address>
</Customer1>
<Customer2>
<Name>Joel</Name>
<Age>32</Age>
<Address>Mapusa</Address>
</Customer2>
</Customers>

关于c# - 如何在 C# 中修改 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038677/

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