2010-01-06 21 views
1

我一直在尝试使用LINQ to XML,并且遇到了一个非常基本的问题。出于某种原因,我在将树转储到System.Console时看不到XML声明。在System.Console上看到XML声明时出现问题

using System; 
using System.Xml.Linq; 

... 

public static void Main(string[] args) 
{ 
    // Build tree. 
    XDocument xd = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 

    // Output tree. 
    System.Console.WriteLine(xd); 

    // Pause. 
    System.Console.ReadLine(); 
} 

有人可以解释我做错了什么基本的东西吗?

感谢,

斯科特

回答

3

添加一些真实的数据到XDoc。并且一定要使用Save()方法来查看整个内容:

XDocument xd = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 
    xd.Add(new XElement("top")); 
    xd.Save(Console.Out); 
+0

保存必须在内存树中调用? – 2010-01-07 01:46:29

+0

呃,不知道你的意思。使用Save()查看完整文档,ToString()不显示所有内容。 – 2010-01-07 02:13:11

+0

啊,好的。让我澄清一下:我认为使用Save()将树中的内存序列化到磁盘上,但是如果它在内存中则不需要对树进行调用。 – 2010-01-08 01:55:12

1

您的文件是空的,所以你只看到一个换行符(将看空)。

尝试添加一些东西到XML文档。这将打印出一个值为XML的文档:

// Build tree. 
XDocument xd = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 
xd.AddFirst(new XElement("root")); 

// Output tree. 
System.Console.WriteLine(xd); 
+0

感谢您的回答! – 2010-01-08 01:56:06