tags:

views:

41

answers:

2

Hi,

I have been experimenting with LINQ to XML and have run across a very basic problem. For some reason, I am not seeing a XML declaration when dumping the tree to System.Console.

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();
}

Can someone explain what basic thing I'm doing wrong ?

Thanks,

Scott

+1  A: 

You document is empty, so you'll just see a newline (which will look blank).

Try adding something to the XML document. This will print out a value XML doc:

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

// Output tree. 
System.Console.WriteLine(xd);
Reed Copsey
Thanks for the answer!
Scott Davies
+3  A: 

Add some real data to the XDoc. And be sure to use the Save() method to see the entire content:

  XDocument xd = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
  xd.Add(new XElement("top"));
  xd.Save(Console.Out);
Hans Passant
Save has to be called on the in memory tree ?
Scott Davies
Erm, not sure what you mean. Use Save() to see the complete document, ToString() doesn't show everything.
Hans Passant
Ah, ok. Let me clarify: I thought Save() was used to serialize the in tree memory to disk but was not required to be called against the tree if it's in memory.
Scott Davies
You don't have to call Save(). You'll get output without it. However, I don't believe you'll get the same output (ie: the declaration will be missing) unless you save it to a stream. nobugz "saved" the file to the Console's output stream, which is a clever way to print it.
Reed Copsey
Thanks for the clarification, Reed!
Scott Davies