tags:

views:

37

answers:

2

I have a XML template file like so

<?xml version="1.0" encoding="us-ascii"?>
<AutomatedDispenseResponse>
    <header shipmentNumber=""></header>
    <items></items>
</AutomatedDispenseResponse>

When I use XDocument.Load, for some reason the

<?xml version="1.0" encoding="us-ascii"?>

is dropped.

How do I load the file into a XDocument and not losing the declaration at the top?

+1  A: 

I suspect it's not really dropping the declaration on load - it's when you're writing the document out that you're missing it. Here's a sample app which works for me:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        Console.WriteLine(doc.Declaration);
    }
}

And test.xml:

<?xml version="1.0" encoding="us-ascii" ?>
<Foo>
  <Bar />
</Foo>

Output:

<?xml version="1.0" encoding="us-ascii"?>

The declaration isn't shown by XDocument.ToString(), and may be replaced when you use XDocument.Save because you may be using something like a TextWriter which already knows which encoding it's using. If you save to a stream or just to a filename, it's preserved in my experience.

Jon Skeet
I figured that out shortly after posting (of course). The intellisense was throwing me off since it was calling ToString(). I just need to do something like http://stackoverflow.com/questions/957124/how-to-print-xml-version1-0-using-xdocument/957161#957161
Kenoyer130
+1  A: 

It is loaded. You can see it and access parts of it using:

XDocument.Parse(myDocument).Declaration
Yuriy Faktorovich