如何强制XDocument在声明行中输出“ UTF-8”?

问题描述 投票:9回答:3

以下代码产生此输出:

<?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
3个回答
16
投票

让我回答我自己的问题,这似乎可行:

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

16
投票

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

有关更多信息,请参见MSDN information about StringWriter.Encoding


0
投票

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

StringWriter.Encoding
© www.soinside.com 2019 - 2024. All rights reserved.