public static XElement CreateCategoriesByXAttribute() 
{ 
XElement root = new XElement("Categories", 
new XElement("Category", 
new XAttribute("CategoryID", Guid.NewGuid()), 
new XElement("CategoryName", "Beverages") 
), 
new XElement("Category", 
new XAttribute("CategoryID", Guid.NewGuid()), 
new XElement("CategoryName", "Condiments") 
), 
new XElement("Category", 
new XAttribute("CategoryID", Guid.NewGuid()), 
new XElement("CategoryName", "Confections") 
) 
); 
root.Save(path); 
return root; 
} 
运行该示例将会得到一个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> 
XAttribute类的方法比较少,常用的三个是:
方法
描述
AddAnnotation
为该属性添加注解
Remove
删除该属性
SetValue
设定该属性的值
以下的示例使用Remove来删除第一个元素的CategoryID属性:
复制代码 代码如下:
 
public static void RemoveAttribute() 
{ 
XElement xdoc = CreateCategoriesByXAttribute(); 
XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID"); 
xattr.Remove(); 
xdoc.Save(path); 
} 
运行该示例将会得到一个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> 
作为尝试,试一试以下删除属性的方法:
复制代码 代码如下:
 
public static void RemoveAttributeByDoc() 
{ 
XElement xdoc = CreateCategoriesByXAttribute(); 
XAttribute xattr = xdoc.Attribute("CategoryID"); 
xattr.Remove(); 
xdoc.Save(path); 
} 
运行该示例将会抛出一个空引用异常,因为元素Categories没有一个叫做CategoryID的属性。
4、XDocument类
XDocument类提供了处理xml文档的方法,包括声明、注释和处理指令。一个XDocument对象可以包含以下内容:
对象
个数
说明
XDeclaration
一个
用于指定xml声明中的重要组成部分,如文档编码和版本等
XElement
一个
指定文档的根元素
XDocumentType
一个
表示一个xml DTD
XComment
多个
Xml注释。它不能是第一个参数,因为一个有效的xml文档不能以注释作为开始
XProcessingInstruction
多个
为处理xml的应用程序指定任何所需信息
下面的示例创建了一个简单的xml文档,它包含几个元素和一个属性,以及一个处理指令和一些注释:
复制代码 代码如下:
 
public static void CreateXDocument() 
{ 
XDocument xdoc = new XDocument( 
new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"), 
new XComment("some comments"), 
new XElement("Root", 
new XElement("Employees", 
new XElement("Employee", 
new XAttribute("id", "1"), 
new XElement("Name", "Scott Klein"), 
new XElement("Title", "Geek"), 
new XElement("HireDate", "02/05/2007"), 
new XElement("Gender", "M") 
) 
) 
), 
new XComment("more comments") 
); 
xdoc.Save(path); 
} 
运行该示例将会得到一个xml文件,其内容为:
复制代码 代码如下:
