您的位置:首页 > 产品设计 > UI/UE

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

2011-04-25 15:28 405 查看
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,将会抛出一个异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐