您的位置:知识库 » 数据库

Linq To Xml学习 - 3.查询、更新、删除

作者: Q.Lee.lulu  来源: 博客园  发布时间: 2008-09-23 17:13  阅读: 45200 次  推荐: 6   原文链接   [收藏]  

 XElement.SetElementValue 方法

此方法旨在简化将名称/值对列表用作子元素集时的维护。维护列表时,需要添加对、修改对或删除对。如果调用此方法将不存在的名称作为子元素传递,则此方法会为您创建一个子元素。如果您调用此方法来传递一个现有子元素的名称,则此方法会将此子元素的值更改为指定的值。如果您为 value 传递了 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing),则此方法会移除子元素。

// Create an element with no content
XElement root = new XElement("Root");

// Add some name/value pairs.
root.SetElementValue("Ele1", 1);
root.SetElementValue("Ele2", 2);
root.SetElementValue("Ele3", 3);
Console.WriteLine(root);

// Modify one of the name/value pairs.
root.SetElementValue("Ele2", 22);
Console.WriteLine(root);

// Remove one of the name/value pairs.
root.SetElementValue("Ele3", null);
Console.WriteLine(root);

输出结果:

<Root>
  <Ele1>1Ele1>
  <Ele2>2Ele2>
  <Ele3>3Ele3>
Root>
<Root>
  <Ele1>1Ele1>
  <Ele2>22Ele2>
  <Ele3>3Ele3>
Root>
<Root>
  <Ele1>1Ele1>
  <Ele2>22Ele2>
Root>

 

XElement.SetAttributeValue 方法

此方法旨在简化将名称/值对列表用作属性集时的维护。维护列表时,需要添加对、修改对或删除对。如果调用此方法将不存在的名称作为属性传递,则此方法会为您创建一个属性。如果调用此方法来传递现有属性的名称,则此方法将会属性的值修改为指定的值。如果您为 value 传递了 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing),则此方法会移除该属性。

此方法将引发 ChangedChanging 事件。

将值分配给具有指定名称的属性。如果不存在具有指定名称的属性,则添加新属性。如果值为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing),则删除具有指定名称的属性(如果存在)。

// Create an element with no content.
XElement root = new XElement("Root");

// Add some name/value pairs.
root.SetAttributeValue("Att1", 1);
root.SetAttributeValue("Att2", 2);
root.SetAttributeValue("Att3", 3);
Console.WriteLine(root);

// Modify one of the name/value pairs.
root.SetAttributeValue("Att2", 22);
Console.WriteLine(root);

// Remove one of the name/value pairs.
root.SetAttributeValue("Att3", null);
Console.WriteLine(root);

输出结果为:

<Root Att1="1" Att2="2" Att3="3" />
<Root Att1="1" Att2="22" Att3="3" />
<Root Att1="1" Att2="22" />
6
0
标签:linq xml

数据库热门文章

    数据库最新文章

      最新新闻

        热门新闻