Kenoyer130
Kenoyer130

Reputation: 7308

XDocument.Load losing Declaration

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?

Upvotes: 2

Views: 3022

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68697

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

XDocument.Parse(myDocument).Declaration

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501163

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.

Upvotes: 3

Related Questions