<?xml version="1.0" encoding="utf-8"?> 
<Categories> 
<Category> 
<CategoryID>1</CategoryID> 
<CategoryName>Beverages</CategoryName> 
</Category> 
</Categories> 
6、处理属性
I.添加
LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者Add方法来添加属性:
复制代码 代码如下:
 
public static void AddAttribute() 
{ 
XElement root = new XElement("Categories", 
new XElement("Category", 
new XAttribute("CategoryID","1"), 
new XElement("CategoryName","Beverages"), 
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales") 
) 
); 
root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString())); 
root.Save(path); 
} 
运行该示例将会得到一个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> 
II.检索
检索属性可以使用Attribute(name)方法:
复制代码 代码如下:
 
public static void SelectAttribute() 
{ 
XElement root = new XElement("Categories", 
new XElement("Category", 
new XAttribute("CategoryID", "1"), 
new XElement("CategoryName", "Beverages"), 
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales") 
) 
); 
XAttribute xattr = root.Element("Category").Attribute("CategoryID"); 
Console.WriteLine(xattr.Name); 
Console.WriteLine(xattr.Value); 
} 
上述代码的运行结果为:
CategoryID
1
III.删除
删除属性的操作是调用XAttribute对象的Remove方法来完成的。
本文总结
本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。
pdf版下载,更容易阅读
您可能感兴趣的文章:
