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?
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:
And test.xml:
Output:
The declaration isn’t shown by
XDocument.ToString(), and may be replaced when you useXDocument.Savebecause you may be using something like aTextWriterwhich already knows which encoding it’s using. If you save to a stream or just to a filename, it’s preserved in my experience.