2010-07-20 37 views
8

下面的代碼產生這樣的輸出:如何強制XDocument在聲明行中輸出「UTF-8」?

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

回答

15

請允許我回答我的問題,這似乎工作:

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

就像API中的一個bug,序列化程序忽略了XDeclaration中的這個值。 – 2013-10-21 15:04:58

+0

@KirkWoll不是真的,因爲XML的默認編碼是UTF8,所以可以省略。因此它引發了爲什麼需要在那裏顯式編寫UTF-8的問題。可能問題是UTF-16存在,而不是UTF-8。 – 2014-06-06 05:49:36

+0

最簡單的解決方案,效果很棒! – BJladu4 2016-02-16 10:23:52

11

這不是在.NET中的錯誤。這是由於您使用StringWriter作爲您的XDocument的目標。由於StringWriter在內部使用UTF-16,因此該文檔還必須使用UTF-16作爲編碼。如果您將XDoc保存到流或文件,它將按照指示使用UTF-8。

有關詳細信息,請參閱MSDN information about StringWriter.Encoding

此屬性是必要的,其中報頭必須包含由StringWriter的所使用的編碼被寫入一些XML方案。這允許XML代碼使用任意的StringWriter並生成正確的XML標題。