linq to xml XDocument和XDeclaration类
XDocument类表示一个XML文档,XDeclaration类表示XML文件中XML声明。其中,XML声明用来声明XML文件的版本、编码,以及XML文件的是否独立。一般情况下,在创建一个XML文件时,需要添加XML声明。
XDocument类提供了多个属性获取XML文件的属性,如获取XML文件的XML声明的Declaration属性、获取XML文件的根元素的Root属性等。XAttribute类的属性如表所示。
表 XDocument类的属性
属 性 |
说 明 |
Declaration |
文件的XML声明。 |
Root |
文件的根元素。 |
DocumentType |
文件的文档类型。 |
NodeType |
文件的节点类型。 |
另外,XDocument类还提供了多个方法操作XML文件,如导入XML文件内容的Load()方法、解释XML文件的Parse()方法等。XAttribute类的方法如表所示。
表 XDocument类的方法
方 法 |
说 明 |
Load |
导入指定地址的XML文件的内容,,并创建为XDocument类实例。 |
Save |
将XDocument类的实例保存为指定地址的XML文件。 |
Parse |
读取指定的XML文件,并解释该XML文件中的内容。 |
XDeclaration类提供了3个属性描述XML声明,具体说明如表所示。
表 XDeclaration类的属性
属 性 |
说 明 |
Version |
XML文件的版本。 |
Encoding |
XML文件的编码。 |
Standalone |
指定XML文件是否独立。 |
下面的实例代码使用XDocument类创建一个XML文件,并保存为“file.xml”文件。其中,该XML文件的根元素为Advertisements元素。根元素又包含两个子元素Ad,Ad元素设置了ID属性、Name和Url元素及其值。具体步骤如下。
(1)创建XDocument类的实例doc,即创建一个XML文件。
(2)使用XDeclaration类创建该XML文件的声明。
(3)使用XElement类创建该XML文件包含的元素Advertisements,以及该元素的子元素及其属性等内容。
(4)调用Save()方法将doc实例保存为XML文件“file.xml”。
(5)使用网页显示“file.xml”文件的内容。
(6)设置网页的输出格式为“text/xml”,并中止网页的输出操作。
private void XDocumentClass() { ///设置新的XML文件保存的地址 string xmlFilePath = Server.MapPath("Data/file.xml"); ///创建一个新的XML文档 XDocument doc = new XDocument( new XDeclaration("1.0","utf-8","yes"), new XElement("Advertisements", new XElement("Ad", new XAttribute("ID","1"), ///添加属性ID new XElement("Name","w3c"), ///添加元素Name new XElement("Url","http://www.w3c.com") ///添加元素Url ), new XElement("Ad", new XAttribute("ID","2"), ///添加属性ID new XElement("Name","Microsoft"), ///添加元素Name new XElement("Url","http://www.microsoft.com") ///添加元素Url ) ) ); ///保存为XML文件 doc.Save(xmlFilePath); ///显示XML文件的内容 Response.Write(doc); ///设置网页显示的形式为XML文件 Response.ContentType = "text/xml"; Response.End(); }
Sample_11项目中的LinqtoXmlBaseClass.aspx页面测试了上述实例代码(XDocumentClass()函数),测试结果如图所示。
来源:http://blog.csdn.net/linqmail/article/details/2341507
加支付宝好友偷能量挖...