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

发布于 2024-09-10 17:49:04 字数 2093 浏览 3 评论 0原文

以下代码产生此输出:

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

The following code produces this output:

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

How can I get it to produce encoding="utf-8" instead of 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);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

聚集的泪 2024-09-17 17:49:05

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

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

You can use the following code as an example

XDocument doc = GetXmlDoc();
using (var stream = new MemoryStream())
{
    doc.Save(stream, SaveOptions.DisableFormatting);
    var docBytes = stream.ToArray();
    File.WriteAllBytes("fileName.xml", docBytes);
}
故笙诉离歌 2024-09-17 17:49:04

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

有关详细信息,请参阅 关于StringWriter.Encoding的MSDN信息:

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

This is not a bug in .NET. This is due to you using StringWriter as the target for your XDocument. Since StringWriter internally uses UTF-16, the document must also use UTF-16 as encoding. If you save the XDoc to a stream or a file, it will use UTF-8 as instructed.

For more information, see MSDN information about StringWriter.Encoding:

This property is necessary for some XML scenarios where a header must be written containing the encoding used by the StringWriter. This allows the XML code to consume an arbitrary StringWriter and generate the correct XML header.

灯下孤影 2024-09-17 17:49:04

让我回答我自己的问题,这似乎有效:

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

Allow me answer my own question, this seems to work:

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文