代码改变世界

Linq to xml 代码实战(2)

2011-12-30 15:44  音乐让我说  阅读(268)  评论(0)    收藏  举报

直接贴代码了:

using System;

namespace ConAppTempTest
{
class Program
{
static void Main(string[] args)
{
XmlDemo2.Test();
}
}
}

 

using System;
using System.Xml.Linq;

namespace ConAppTempTest
{
public class XmlDemo2
{
private static readonly string XmlFilePath = @"D:\animals.xml";

public static void Test()
{
TestCreateXElementTree();
}

private static void TestCreateXElementTree()
{
XDocument d = new XDocument(
new XComment("这里是评论"),
new XProcessingInstruction("xml-stylesheet",
"href='mystyle.css' title='Compact' type='text/css'"),
new XElement("Pubs",
new XElement("Book",
new XElement("Title", "Linq 实战"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "C# 高级编程"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("这里是另外的评论")
);
d.Declaration = new XDeclaration("1.0", "utf-8", "true");
Console.WriteLine(d);

d.Save(XmlFilePath);

}
}
}

 

D:\animals.xml 中的 XML 文件内容:

<?xml version="1.0" encoding="utf-8"?>
<!--这里是评论-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs>
<Book>
<Title>Linq 实战</Title>
<Author>Moreno, Jordao</Author>
</Book>
<Book>
<Title>C# 高级编程</Title>
<Author>Gazit, Inbar</Author>
</Book>
</Pubs>
<!--这里是另外的评论-->

 

不知道你注意了没有,就是 截图中打印出来的没有 XML 声明,而保存的 XML 文件中却有。

运行截图:

谢谢浏览!