【问题标题】:How can I force XDocument to output "UTF-8" in the declaration line?如何强制 XDocument 在声明行中输出“UTF-8”?
【发布时间】:2011-03-18 07:52:28
【问题描述】:

以下代码产生此输出:

<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<customers>
  <customer>
    <firstName>Jim</firstName>
    <lastName>Smith</lastName>
  </customer>
</customers>

我怎样才能让它产生encoding="utf-8"而不是encoding="utf-16"?

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace test_xml2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer> {
                new Customer {FirstName="Jim", LastName="Smith", Age=27},
                new Customer {FirstName="Hank", LastName="Moore", Age=28},
                new Customer {FirstName="Jay", LastName="Smythe", Age=44},
                new Customer {FirstName="Angie", LastName="Thompson", Age=25},
                new Customer {FirstName="Sarah", LastName="Conners", Age=66}
            };

            Console.WriteLine(BuildXmlWithLINQ(customers));

            Console.ReadLine();

        }
        private static string BuildXmlWithLINQ(List<Customer> customers)
        {
            XDocument xdoc =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement("customers",
                        new XElement("customer",
                            new XElement("firstName", "Jim"),
                            new XElement("lastName", "Smith")
                        )
                    )
                );

            var wr = new StringWriter();
            xdoc.Save(wr);

            return wr.GetStringBuilder().ToString();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public string Display()
        {
            return String.Format("{0}, {1} ({2})", LastName, FirstName, Age);
        }
    }
}

【问题讨论】:

    标签: c# xml utf-8 linq-to-xml


    【解决方案1】:

    这不是 .NET 中的错误。这是因为您使用StringWriter 作为 XDocument 的目标。由于 StringWriter 内部使用 UTF-16,因此文档也必须使用 UTF-16 作为编码。如果您将 XDoc 保存到流或文件中,它将按照说明使用 UTF-8。

    更多信息请见MSDN information about StringWriter.Encoding:

    对于某些必须写入包含 StringWriter 使用的编码的标头的 XML 场景,此属性是必需的。这允许 XML 代码使用任意 StringWriter 并生成正确的 XML 标头。

    【讨论】:

      【解决方案2】:

      请允许我回答我自己的问题,这似乎可行:

      private static string BuildXmlWithLINQ()
      {
          XDocument xdoc = new XDocument
          (
              new XDeclaration("1.0", "utf-8", "yes"),
              new XElement("customers",
                  new XElement("customer",
                      new XElement("firstName", "Jim"),
                      new XElement("lastName", "Smith")
                  )
              )
          );
          return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
      }
      

      【讨论】:

      • 对我来说,这似乎是 API 中的一个错误,即序列化程序忽略了您的 XDeclaration 中的这个值。
      • @KirkWoll 并非如此,因为 XML 的默认编码是 UTF8,因此可以省略。因此它引出了一个问题,为什么需要在那里显式编写 UTF-8。问题可能是存在 UTF-16,而不是没有 UTF-8。
      【解决方案3】:

      您可以使用以下代码作为示例

      XDocument doc = GetXmlDoc();
      using (var stream = new MemoryStream())
      {
          doc.Save(stream, SaveOptions.DisableFormatting);
          var docBytes = stream.ToArray();
          File.WriteAllBytes("fileName.xml", docBytes);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-03-11
        • 2011-04-21
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多