为什么XDeclaration会忽略我设置的编码参数

时间:2014-11-12 15:29:28

标签: c# asp.net xml

问题

我正在尝试使用XDeclaration生成一个XML文件,该文件应该会生成以下内容

<?xml version="1.0"?>

当我运行我的代码时,我一直得到的是

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

所以问题是,无论我在XDeclaration的编码参数中更改了什么,它都会在我的声明中添加编码标记。

我的问题

我想要的甚至可能吗?如果是这样,有人可以向我解释一下吗?

我尝试了什么

首先,我尝试将OmitXmlDeclaration设置为true。但这完全取消了我的声明,然后根本就不能使用XDecleration ..

其次,当我将XDecleration设置为:

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

我明白了

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

当我将XDecleration设置为:

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

我明白了

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

所以我知道它确实响应我输入的内容,但编码部分没有。 编辑:我还尝试将参数设置为null而不是string.Empty。这也不起作用。

我的代码

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

修改

解决方案是由@HimBromBeere给我的。他回答了以下链接。

cookcomputing.com/blog/archives/000577.html。在这里,您可以覆盖编码参数。这对我有用。

1 个答案:

答案 0 :(得分:0)

默认情况下,XML保存方法会在保存Xdocument时覆盖我们通过XDeclaration提供的编码方法。最简单的方法是创建一个内存流并修补编码方法。请参阅以下代码片段

public static void PatchEncoding(string xmlPath,  XDocument xmlDoc, string encoding = "windows-1251")
{
        using (var stream = new MemoryStream())
        using (XmlTextWriter xmlwriter = new XmlTextWriter(stream, Encoding.GetEncoding(encoding)))
        {
            xmlDoc.Save(xmlPath);
        }
}