Các mã sau đây tạo ra sản lượng này:Làm thế nào tôi có thể buộc XDocument xuất ra "UTF-8" trong dòng khai báo?
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<customers>
<customer>
<firstName>Jim</firstName>
<lastName>Smith</lastName>
</customer>
</customers>
Làm thế nào tôi có thể lấy nó để sản xuất encoding="utf-8"
thay vì 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);
}
}
}
Dường như một lỗi trong API cho tôi rằng trình tuần tự bỏ qua giá trị này trong 'XDeclaration' của bạn. –
@KirkWoll Không thực sự, vì mã hóa mặc định cho XML là UTF8 nên nó có thể được bỏ qua. Do đó, nó đặt ra câu hỏi tại sao nhu cầu viết UTF-8 rõ ràng ở đó. Có lẽ vấn đề là UTF-16 ở đó, không phải là không có UTF-8. –
giải pháp đơn giản nhất và hoạt động tuyệt vời! – BJladu4