gpt4 book ai didi

C# Linq to XML 添加、更新、删除

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

我有这个代码

        XElement newClient= new XElement("Client",
new XElement("Name", cmbClient.Text),
new XElement("Service",
new XElement("ServName", cmbService.Text)));
xmlDoc.Add(newClient);
xmlDoc.Save("Settings.xml");

这是什么造成的

<?xml version="1.0" encoding="utf-8"?>
<Clients>
<Client>
<Name>Client Name</Name>
<Services>
<ServName>Service Name</ServName>
</Services>
</Client>
</Clients>

如果我再次按下 Button1,那么它将创建另一个客户端部分,没关系,但我想要的是:

  1. 如果不存在,则创建一个新的客户部分。
  2. 如果 Client 存在,则向其添加一个 ServName,而不是替换已经有了。
  3. 如果客户端上已经存在服务,则什么都不做,因为已经存在。

有什么线索吗?我从 linq to xml 开始……感谢您的建议!

编辑:解决方案由 Dmitry Dovgopoly 和 Leon Newswanger 的 mixin 答案提供,谢谢两位! :D

XDocument xDoc = XDocument.Load("Settings.xml");
var Clients =
from client in xDoc.Root.Elements("Client")
where client.Element("Name").Value == cmbClient.Text
select client;
if (Clients.Count() > 0)
{
var Client =
(from client in xDoc.Root.Elements("Client")
where client.Element("Name").Value == cmbClient.Text
select client).Single();
if (Client.Element("Services").Elements().Count(el => el.Value == cmbService.Text) == 0)
{
Client.Element("Services").Add(new XElement("ServName", cmbService.Text));
}
}
else
{
XElement newClient = new XElement("Client",
new XElement("Name", cmbClient.Text),
new XElement("Services",
new XElement("ServName", cmbService.Text)));
xDoc.Root.Add(newClient);
}
xDoc.Save("Settings.xml");

最佳答案

您可以使用XElement.Element(name) 方法获取特定元素或使用XElement.Elements() 枚举所有元素。

if (xmlDoc.Elements("Client").Count() == 0)
{
//Client section does not exist. We add new section.
XElement newClient = new XElement("Client",
new XElement("Name", mbClient.Text),
new XElement("Service",
new XElement("ServName", cmbService.Text)));
xmlDoc.Add(newClient);
}
else //Client section exists.
{
//obtain <service> section
XElement service = xmlDoc.Element("Client").Element("Service");

if (service.Elements().Count(el => el.Value == cmbService.Text) == 0)
{
//there is no service with name cmbService.Text. We add one.
service.Add(new XElement("ServName", cmbService.Text));
}
}

关于C# Linq to XML 添加、更新、删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13289320/

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