I try to create the below line above all of the files by using 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 :
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. Use XDocument.Save
, eg:
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. If you want to serialize the XDocument
to a UTF-8 byte array, then eg:
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 doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes")
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.