[英]xml.Linq: "Name cannot begin with the '?' character, hexadecimal value 0x3F"
I try to create the below line above all of the files by using System.Xml.Linq我尝试使用 System.Xml.Linq 在所有文件上方创建以下行
<?xml version="1.0" encoding="utf-8"?>
and here is the code这是代码
var firstLine = new XElement(
"?xml",
new XAttribute("version", "1.0"),
new XAttribute("encoding", "UTF-8"),
"?");
but after the run, I get the below error但运行后,我收到以下错误
result Message: System.Xml.XmlException: Name cannot begin with the '?' character, hexadecimal value 0x3F.
I wonder if anyone knows how I can solve this?我想知道是否有人知道我该如何解决这个问题?
That's an XML Declaration, represented by the XDeclaration
type :这是一个 XML 声明,由
XDeclaration
类型表示:
An example, from this doc :一个例子,来自这个文档:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root", "content")
);
Note that XDocument.ToString()
will omit the declaration.请注意,
XDocument.ToString()
将省略声明。 Use XDocument.Save
, eg:使用
XDocument.Save
,例如:
using (var writer = new StringWriter())
{
doc.Save(writer);
Console.WriteLine(writer.ToString());
}
Note however that you'll get encoding="utf-16"
in this case, because strings in .NET are UTF-16.但是请注意,在这种情况下您将得到
encoding="utf-16"
,因为 .NET 中的字符串是 UTF-16。 If you want to serialize the XDocument
to a UTF-8 byte array, then eg:如果要将
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"?>.
to do so you need an XDeclaration with XDocument为此,您需要一个带有XDocument的XDeclaration
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes")
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.