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

时间:2020-11-09 09:05:00

标签: c# xml

我尝试使用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.

我想知道是否有人知道我该如何解决?

2 个答案:

答案 0 :(得分:2)

这是一个XML声明,由XDeclaration type表示:

一个示例,来自this doc

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

答案 1 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>. 

为此,您需要带有 XDocument

XDeclaration
XDocument doc = new XDocument(  
    new XDeclaration("1.0", "utf-8", "yes")
);  
相关问题