繁体   English   中英

xml.Linq:“名称不能以 '?' 开头字符,十六进制值 0x3F"

[英]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"?>. 

为此,您需要一个带有XDocumentXDeclaration

XDocument doc = new XDocument(  
    new XDeclaration("1.0", "utf-8", "yes")
);  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM