Why does XDecleration ignores the encoding parameter i set



The problem


I am trying to generate a XML file with the XDeclaration that should spit out the following


<?xml version="1.0"?>.


What I keep getting when I run my piece of code is this


<?xml version="1.0" encoding="utf-8"?>.


So the problem is, no matter what I change in the encoding parameter of my XDecleration it keeps adding a encoding tag to my declaration.


My question


Is what I want even possible? And if so could someone explain it to me?


What I have tried


First I tried to set OmitXmlDeclaration to true. But that removes my declaration entirely and then I can't use the XDecleration class at all..


Secondly, when I set my XDecleration to this:



new XDeclaration("1.0", string.Empty, "yes")


I get this



<?xml version="1.0" encoding="utf-8" standalone="yes"?>


and when I set my XDecleration to this:



new XDeclaration("1.0", string.Empty, string.Empty)


I get this



<?xml version="1.0" encoding="utf-8"?>


So I know that it does respond to what I enter, but the encoding part is not.


My Code



public FileResult Download()
{
var doc = new XDocument(
new XDeclaration("1.0", string.Empty, string.Empty),
new XElement("foo",
new XAttribute("hello", "world")
)
);

using (var stream = new MemoryStream())
{
var settings = new XmlWriterSettings()
{
OmitXmlDeclaration = false,
Indent = true,
};

using (var writer = XmlWriter.Create(stream, settings))
{
doc.Save(writer);
}

stream.Position = 0;

return File(stream.ToArray(), "text/xml", "HelloWorld.xml");
}
}

No comments:

Post a Comment