[代码]创建XDocument对象(LINQ to XML)

本文介绍如何使用LINQ to XML创建一个包含注释、处理指令和元素的XML文档。示例展示了如何构建XDocument对象,并将其内容输出到控制台及保存为文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LINQ to XML中的XDocument是用来表示内存中的XML文档的。同样可以使用函数构造功能来创建此对象。
此示例代码主要用来演示如何创建一个通用的XML文档。

示例代码
代码中创建的XDocument对象,包含了2个注释(XComment),1个处理指令(XProcessingInstrucation),1个根元素及其若干子元素,也为文档添加了XML声明(XDeclaration)。最将所生成的XML内容打印到控制台,并保存到文件中。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Demo05 { class Program { static void Main(string[] args) { XDocument Document = new XDocument( new XComment("This is a comment."), new XProcessingInstruction("xml-stylesheet", "href='mystyle.css' title='Compact' type='text/css'"), new XElement("Pubs", new XElement("Book", new XElement("Title", "Artifacts of Roman Civilization"), new XElement("Author", "Moreno, Jordao")), new XElement("Book", new XElement("Title", "Midieval Tools and Implements"), new XElement("Author", "Gazit, Inbar"))), new XComment("This is another comment.")); Document.Declaration = new XDeclaration("1.0", "utf-8", "true"); Console.WriteLine(Document); Document.Save(@"C:/LINQ/XDocument.xml"); } } }
打印到控制台,以及保存到XDocument.xml文件中的XML内容如下:
<?xml version="1.0" encoding="utf-8"?> <!--This is a comment.--> <?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?> <Pubs> <Book> <Title>Artifacts of Roman Civilization</Title> <Author>Moreno, Jordao</Author> </Book> <Book> <Title>Midieval Tools and Implements</Title> <Author>Gazit, Inbar</Author> </Book> </Pubs> <!--This is another comment.-->
怎么样,是不是挺帅的!^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值