您的位置:首页 > 编程语言

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

2010-10-27 18:41 387 查看
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.-->

怎么样,是不是挺帅的!^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: