LINQ To XML:设置子元素的值、添加子元素或移除子元素(XElement.SetElementValue)

本文介绍XElement.SetElementValue方法的使用技巧,包括更新、添加和删除XML元素的操作方式,并强调了将元素值设置为null的效果及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XElement.SetElementValue这个方法相当的体贴,它会自动判断元素是否有该子元素,如果有就是更新,没有就是增加,那么删除呢,也简单得让人开心的笑,XElement.SetElementValue("LastName", null),这句是删除LastName这个元素

// we will use this to store a reference to one of the elements in the XML tree. XElement firstParticipant; XDocument xDocument = new XDocument( new XElement("BookParticipants", firstParticipant = new XElement("BookParticipant", new XAttribute("type", "Author"), new XElement("FirstName", "Joe"), new XElement("LastName", "Rattz")))); Console.WriteLine(System.Environment.NewLine + "Before updating elements:"); Console.WriteLine(xDocument); // First, we will use XElement.SetElementValue to update the value of an element. // Since an element named FirstName is there, its value will be updated to Joseph. firstParticipant.SetElementValue("FirstName", "Joseph"); // Second, we will use XElement.SetElementValue to add an element. // Since no element named MiddleInitial exists, one will be added. firstParticipant.SetElementValue("MiddleInitial", "C"); // Third, we will use XElement.SetElementValue to remove an element. // Setting an element's value to null will remove it. firstParticipant.SetElementValue("LastName", null); Console.WriteLine(System.Environment.NewLine + "After updating elements:"); Console.WriteLine(xDocument);

输出

Before updating elements: <BookParticipants> <BookParticipant type="Author"> <FirstName>Joe</FirstName> <LastName>Rattz</LastName> </BookParticipant> </BookParticipants> After updating elements: <BookParticipants> <BookParticipant type="Author"> <FirstName>Joseph</FirstName> <MiddleInitial>C</MiddleInitial> </BookParticipant> </BookParticipants>

对于这个方法,作者也提出一个警示

Just because calling the SetElementValue method with a value of null removes the node, don’t

make the mistake of thinking that manually setting an element’s value to null is the same as removing it in the

LINQ to XML API. This is merely the behavior of the SetElementValue method. If you attempt to set an element’s

value to null using its Value property, an exception will be thrown.

不要天真的认为SetElementValue 方法把一个元素设为NULL是删除,那么你手动把一个元素的值设为NULL就可以删除那个结点

如果你企图设置那个元素的值为NULL,将会抛出一个异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值