首页 > 代码库 > LINQ to XML 编程基础

LINQ to XML 编程基础

 

1、LINQ to XML类

 

技术分享

 

以下的代码演示了如何使用LINQ to XML来快速创建一个xml:

隐藏行号 复制代码 创建 XML
  1. public static void CreateDocument()
  2. {
  3.     string path = @"d:\website";
  4.     XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
  5.                                    new XElement("Root", "root"));
  6.     xdoc.Save(path);
  7. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>root</Root>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

2、XElement类

XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与 System.Xml 中的其他类(例如 XmlReader、XmlWriter 和 XslCompiledTransform)进行互操作。

使用LINQ to XML创建xml文档有很多种方式,具体使用哪种方法要根据实际需要。而创建xml文档最简单、最常见的方式是使用XElement类。以下的代码演示了如何使用XElement类创建一个xml文档:

 

显示行号 复制代码 这是一段程序代码。
  1. public static void CreateCategories()
  2. {
  3.     string path = @"d:\website";
  4.     XElement root = new XElement("Categories",
  5.         new XElement("Category",
  6.             new XElement("CategoryID", Guid.NewGuid()),
  7.             new XElement("CategoryName", "Beverages")
  8.             ),
  9.         new XElement("Category",
  10.             new XElement("CategoryID", Guid.NewGuid()),
  11.             new XElement("CategoryName", "Condiments")
  12.             ),
  13.         new XElement("Category",
  14.             new XElement("CategoryID", Guid.NewGuid()),
  15.             new XElement("CategoryName", "Confections")
  16.             )
  17.        );
  18.     root.Save(path);
  19. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>
    <CategoryName>Beverages</CategoryName>
  </Category>
  <Category>
    <CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>
    <CategoryName>Condiments</CategoryName>
  </Category>
  <Category>
    <CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>
    <CategoryName>Confections</CategoryName>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

XElement类包含了许多方法,这些方法使得处理xml变得轻而易举。有关这些方法请参照MSDN。

其中,Save、CreateReader、ToString和WriteTo方法是比较常用的三个方法:

技术分享

 

3、XAttribute类

 

XAttribute类用来处理元素的属性,属性是与元素相关联的“名称-值”对,每个元素中不能有名称重复的属性。使用XAttribute类与使用XElement类的操作十分相似,下面的示例演示了如何在创建xml树时为其添加一个属性:

显示行号 复制代码 这是一段程序代码。
  1. public static XElement CreateCategoriesByXAttribute()
  2. {
  3.     XElement root = new XElement("Categories",
  4.         new XElement("Category",
  5.             new XAttribute("CategoryID", Guid.NewGuid()),
  6.             new XElement("CategoryName", "Beverages")
  7.             ),
  8.         new XElement("Category",
  9.             new XAttribute("CategoryID", Guid.NewGuid()),
  10.             new XElement("CategoryName", "Condiments")
  11.             ),
  12.         new XElement("Category",
  13.             new XAttribute("CategoryID", Guid.NewGuid()),
  14.             new XElement("CategoryName", "Confections")
  15.             )
  16.        );
  17.     root.Save(path);
  18.     return root;
  19. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">
    <CategoryName>Beverages</CategoryName>
  </Category>
  <Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">
    <CategoryName>Condiments</CategoryName>
  </Category>
  <Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">
    <CategoryName>Confections</CategoryName>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

XAttribute类的方法比较少,常用的三个是:

技术分享

 

以下的示例使用Remove来删除第一个元素的CategoryID属性:

显示行号 复制代码 这是一段程序代码。
  1. public static void RemoveAttribute()
  2. {
  3.     XElement xdoc = CreateCategoriesByXAttribute();
  4.     XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");
  5.     xattr.Remove();
  6.     xdoc.Save(path);
  7. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryName>Beverages</CategoryName>
  </Category>
  <Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">
    <CategoryName>Condiments</CategoryName>
  </Category>
  <Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">
    <CategoryName>Confections</CategoryName>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

作为尝试,试一试以下删除属性的方法:

显示行号 复制代码 这是一段程序代码。
  1. public static void RemoveAttributeByDoc()
  2. {
  3.     XElement xdoc = CreateCategoriesByXAttribute();
  4.     XAttribute xattr = xdoc.Attribute("CategoryID");
  5.     xattr.Remove();
  6.     xdoc.Save(path);
  7. }

<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>运行该示例将会抛出一个空引用异常,因为元素Categories没有一个叫做CategoryID的属性。

 

4、XDocument类

 

XDocument类提供了处理xml文档的方法,包括声明、注释和处理指令。一个XDocument对象可以包含以下内容:

技术分享

下面的示例创建了一个简单的xml文档,它包含几个元素和一个属性,以及一个处理指令和一些注释:

显示行号 复制代码 这是一段程序代码。
  1. public static void CreateXDocument()
  2.       {
  3.           XDocument xdoc = new XDocument(
  4.                   new XProcessingInstruction("xml-stylesheet", "title=‘EmpInfo‘"),
  5.                   new XComment("some comments"),
  6.                   new XElement("Root",
  7.                           new XElement("Employees",
  8.                                   new XElement("Employee",
  9.                                           new XAttribute("id", "1"),
  10.                                           new XElement("Name", "Scott Klein"),
  11.                                           new XElement("Title", "Geek"),
  12.                                           new XElement("HireDate", "02/05/2007"),
  13.                                           new XElement("Gender", "M")
  14.                                       )
  15.                               )
  16.                       ),
  17.                   new XComment("more comments")
  18.               );
  19.           xdoc.Save(path);
  20.       }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet title=‘EmpInfo‘?>
<!--some comments-->
<Root>
  <Employees>
    <Employee id="1">
      <Name>Scott Klein</Name>
      <Title>Geek</Title>
      <HireDate>02/05/2007</HireDate>
      <Gender>M</Gender>
    </Employee>
  </Employees>
</Root>
<!--more comments-->
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

XDocument类包含多个与XElement类相同的方法,具体内容可以参阅MSDN。需要注意的是,处理节点和元素的大部分功能都可以通过XElement获得,只有当绝对需要文档层次的处理能力,以及需要访问注释、处理指令和声明时,才有使用XDocument类的必要。

 

创建了xml文档后,可以使用NodesAfterSelf方法返回指定的XElement元素之后的所有同级元素。需要注意的是,此方法只包括返回集合中的同级元素,而不包括子代。此方法使用延迟执行。以下代码演示了这一过程:

显示行号 复制代码 这是一段程序代码。
  1. public static void NodesAfterSelf()
  2. {
  3.     XElement root = new XElement("Categories",
  4.         new XElement("Category",
  5.                 new XElement("CategoryID", Guid.NewGuid()),
  6.                 new XElement("CategoryName", "食品"),
  7.                 new XElement("Description", "可以吃的东西")
  8.             )
  9.         );
  10.     foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())
  11.     {
  12.         Console.WriteLine((item as XElement).Value);
  13.     }
  14. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

 

 

二、LINQ to XML编程概念

 

本节将介绍LINQ to XML编程的相关概念,例如如何加载xml、创建全新xml、操纵xml的信息以及遍历xml文档。

 

1、加载已有的xml

使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。

下面的示例演示了如何从文件中加载xml:

显示行号 复制代码 这是一段程序代码。
  1. public static void LoadFromFile()
  2. {
  3.     XElement root = XElement.Load(path);
  4.     Console.WriteLine(root.ToString());
  5. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

也可以使用Parse方法从一个字符串加载xml:

显示行号 复制代码 这是一段程序代码。
  1.     public static void LoadFromString()
  2.     {
  3.         XElement root = XElement.Parse(@"
  4.     <Categories>
  5.       <Category>
  6.         <CategoryID>1</CategoryID>
  7.         <CategoryName>Beverages</CategoryName>
  8.         <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  9.       </Category>
  10.     </Categories>
  11. ");
  12.         Console.WriteLine(root.ToString());
  13.     }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

 

2、保存xml

在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。

 

3、创建xml

在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。

 

4、遍历xml

使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历xml树,并获取指定元素的方式:

显示行号 复制代码 这是一段程序代码。
  1. public static void Enum()
  2. {
  3.     XElement root = new XElement("Categories");
  4.     using (NorthwindDataContext db = new NorthwindDataContext())
  5.     {
  6.         root.Add(
  7.                 db.Categories
  8.                 .Select
  9.                 (
  10.                     c => new XElement
  11.                     (
  12.                         "Category"
  13.                         , new XElement("CategoryName", c.CategoryName)
  14.                     )
  15.                 )
  16.             );
  17.     }
  18.     foreach (var item in root.Elements("Category"))
  19.     {
  20.         Console.WriteLine(item.Element("CategoryName").Value);
  21.     }
  22. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

上述代码运行的结果为:

技术分享 

是不是很简单呢?Nodes()、Elements()、Element(name)和Elements(name)方法为xml树的导航提供了基本功能。

 

5、操纵xml

LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。

I.插入

使用XNode类的插入方法可以方便地向xml树添加内容:

技术分享

在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:

显示行号 复制代码 这是一段程序代码。
  1. public static void AddAfterSelf()
  2. {
  3.     XElement root = XElement.Parse(@"
  4.         <Categories>
  5.           <Category>
  6.             <CategoryID>1</CategoryID>
  7.             <CategoryName>Beverages</CategoryName>
  8.             <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  9.           </Category>
  10.         </Categories>
  11.     ");
  12.     XElement xele = root.Element("Category").Element("CategoryName");
  13.     xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
  14.     root.Save(path);
  15. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryID>1</CategoryID>
    <CategoryName>Beverages</CategoryName>
    <AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>
    <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。

 

II.更新

在LINQ to XML中更新xml内容可以使用以下几种方法:

技术分享

在下面的示例中使用了ReplaceWith与SetElementValue方法对xml进行了更新操作:

显示行号 复制代码 这是一段程序代码。
  1. public static void Update()
  2. {
  3.     XElement root = XElement.Parse(@"
  4.                                    <Categories>
  5.                                       <Category>
  6.                                         <CategoryID>1</CategoryID>
  7.                                         <CategoryName>Beverages</CategoryName>
  8.                                         <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  9.                                       </Category>
  10.                                     </Categories>
  11.                                   ");
  12.     root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));
  13.     root.Element("Category").SetElementValue("CategoryName", "test data");
  14.     root.Save(path);
  15. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <ID>2</ID>
    <CategoryName>test data</CategoryName>
    <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

III.删除

可以使用Remove(XElement)与RemoveAll方法来删除xml。

在下面的示例中,使用了RemoveAll方法:

显示行号 复制代码 这是一段程序代码。
  1. }
  2.   public static void Remove()
  3.   {
  4.       string path = @"d:\";
  5.       XElement root = XElement.Parse(@"
  6.                                   <Categories>
  7.                                     <Category>
  8.                                       <CategoryID>1</CategoryID>
  9.                                       <CategoryName>Beverages</CategoryName>
  10.                                       <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  11.                                     </Category>
  12.                                   </Categories>
  13.                                 ");
  14.       root.RemoveAll();
  15.       root.Save(path);
  16.   }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories />
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

在下面的示例中,使用了Remove方法删除了xml的Description元素:

显示行号 复制代码 这是一段程序代码。
  1. public static void Remove()
  2. {
  3.     XElement root = XElement.Parse(@"
  4.                                 <Categories>
  5.                                   <Category>
  6.                                     <CategoryID>1</CategoryID>
  7.                                     <CategoryName>Beverages</CategoryName>
  8.                                     <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  9.                                   </Category>
  10.                                 </Categories>
  11.                                 ");
  12.     root.Element("Category").Element("Description").Remove();
  13.     root.Save(path);
  14. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryID>1</CategoryID>
    <CategoryName>Beverages</CategoryName>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

6、处理属性

I.添加

LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者Add方法来添加属性:

显示行号 复制代码 这是一段程序代码。
  1. public static void AddAttribute()
  2. {
  3.     XElement root = new XElement("Categories",
  4.         new XElement("Category",
  5.             new XAttribute("CategoryID", "1"),
  6.             new XElement("CategoryName", "Beverages"),
  7.             new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
  8.         )
  9.     );
  10.     root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()));
  11.     root.Save(path);
  12. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category CategoryID="1" AddDate="2010-01-31">
    <CategoryName>Beverages</CategoryName>
    <Description>Soft drinks, coffees, teas, beers, and ales</Description>
  </Category>
</Categories>
<style type="text/css"> .codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif} .codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal} .codearea pre.alt{ background-color:#f7f7ff !important} .codearea .lnum{color:#4f81bd;line-height:18px} </style>

 

II.检索

检索属性可以使用Attribute(name)方法:

显示行号 复制代码 这是一段程序代码。
  1. public static void SelectAttribute()
  2. {
  3.     XElement root = new XElement("Categories",
  4.         new XElement("Category",
  5.             new XAttribute("CategoryID", "1"),
  6.             new XElement("CategoryName", "Beverages"),
  7.             new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
  8.         )
  9.     );
  10.     XAttribute xattr = root.Element("Category").Attribute("CategoryID");
  11.     Console.WriteLine(xattr.Name);
  12.     Console.WriteLine(xattr.Value);
  13. }
<style type="text/css"> .src_container{background-color:#e7e5dc; width:99%; overflow:hidden; margin:12px 0 12px 0 !important; padding:0px 3px 3px 0px} .src_container .titlebar{ background-color:#d4dfff; border:1px solid #4f81bd; border-bottom:0; padding:3px 24px; margin:0; width:auto; line-height:120%; overflow:hidden; text-align:left; font-size:12px} .src_container .toolbar{ display:inline; font-weight:normal; font-size:100%; float:right; cursor:hand; color:#00f; text-align:left; overflow:hidden} .toolbar span.button{ display:inline; font-weight:normal; font-size:100%; cursor:hand; color:#00f; text-align:left; overflow:hidden; cursor:pointer;} .src_container div.clientarea{ background-color:white; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; height:auto; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys",courier,monospace,serif} .src_container ol.mainarea{ padding:0 0 0 52px; margin:0; background-color:#f7f7ff !important} .number_show{ padding-left:52px !important; list-style:decimal outside !important} .number_show li{ list-style:decimal outside !important; border-left:1px dotted #4f81bd} .number_hide{ padding-left:0px !important; list-style-type:none !important} .number_hide li{ list-style-type:none !important; border-left:0px} ol.mainarea li{ display:list-item !important; font-size:12px !important; margin:0 !important; line-height:18px !important; padding:0 0 0 0px !important; background-color:#f7f7ff !important; color:#4f81bd} ol.mainarea li pre{color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important} .linewrap ol.mainarea li pre{white-space:pre-wrap; white-space:-moz-pre-wrapwhite-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word} ol.mainarea li pre.alt{ background-color:#f7f7ff !important} </style><script language="javascript"> function CopyCode(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){var content=codeElement.innerText;if(window.clipboardData=http://www.mamicode.com/=null){window.alert("您的浏览器不支持脚本复制,请尝试手动复制。")}else{window.clipboardData.setData("Text",content);window.alert("源代码已经复制到剪贴板上。")}}}function LineNumberVisible(key){var codeElement=null;var trElements=document.all.tags("ol");var i;for(i=0;i<trElements.length;++i){if(key.parentElement.parentElement.parentElement==trElements[i].parentElement.parentElement){codeElement=trElements[i];break}}if(codeElement!=null){if(codeElement.className=="mainarea number_hide"){codeElement.className="mainarea number_show";key.innerText="隐藏行号"}else{codeElement.className="mainarea number_hide";key.innerText="显示行号"}}}function ChangeIcon(key,isHover){if(isHover)key.style.color=‘red‘;else key.style.color=‘blue‘}function CopyCode_CheckKey(key){if(window.event.keyCode==13)CopyCode(key)}function AboutMe(){window.alert("本代码框由 CodePaste for Windows Live Writer 生成。\r\n\r\nAuthor: 范传根\r\nEmail: chuangen@live.cn\r\nWebsite: http://chuangen.name\r\nBlog: http://blog.csdn.net/chuangen");} </script>

上述代码的运行结果为:

CategoryID

1

 

本文总结

 

本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。 

LINQ to XML 编程基础