[英]Name cannot begin with the '1' character, hexadecimal value 0x31. while reading from an xml file
[英]xml.Linq: "Name cannot begin with the '?' character, hexadecimal value 0x3F"
我嘗試使用 System.Xml.Linq 在所有文件上方創建以下行
<?xml version="1.0" encoding="utf-8"?>
這是代碼
var firstLine = new XElement(
"?xml",
new XAttribute("version", "1.0"),
new XAttribute("encoding", "UTF-8"),
"?");
但運行后,我收到以下錯誤
result Message: System.Xml.XmlException: Name cannot begin with the '?' character, hexadecimal value 0x3F.
我想知道是否有人知道我該如何解決這個問題?
這是一個 XML 聲明,由XDeclaration
類型表示:
一個例子,來自這個文檔:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root", "content")
);
請注意, XDocument.ToString()
將省略聲明。 使用XDocument.Save
,例如:
using (var writer = new StringWriter())
{
doc.Save(writer);
Console.WriteLine(writer.ToString());
}
但是請注意,在這種情況下您將得到encoding="utf-16"
,因為 .NET 中的字符串是 UTF-16。 如果要將XDocument
序列化為 UTF-8 字節數組,則例如:
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
doc.Save(writer);
}
var utf8ByteArray = stream.ToArray();
Console.WriteLine(Encoding.UTF8.GetString(utf8ByteArray));
}
<?xml version="1.0" encoding="utf-8"?>.
為此,您需要一個帶有XDocument的XDeclaration
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes")
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.