【问题标题】:xml.Linq: "Name cannot begin with the '?' character, hexadecimal value 0x3F"xml.Linq:“名称不能以 '?' 开头字符,十六进制值 0x3F"
【发布时间】:2020-11-09 09:05:00
【问题描述】:

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

不知道有没有人知道如何解决这个问题?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    这是一个 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));
    }
    

    【讨论】:

    • 感谢您的快速回复!我可以看到它已被添加。但我想知道为什么在向此 XDocument 添加 XElemnt 后不再包含该行!!!
    • @ShrnPrmshr 是的,ToString() 省略了声明,see herehere。使用XDocument.Save。查看我的编辑
    • 天啊,很多事情我都不知道。这非常有帮助,非常感谢!我所有的问题都已经解决了。我想知道您是否知道如何在版本和编码之间添加换行符?我试过\n,但它确实有效。
    • @ShrnPrmshr You can't。您也许可以继承 XDeclaration 并覆盖 ToString 但是......值得一试。
    • 我可以猜到,但是除了这个根以外的其他行呢?我希望能够在每个属性之间添加换行符,甚至有时在某些文本中为下一行添加换行符。看来\n根本不起作用
    【解决方案2】:
    <?xml version="1.0" encoding="utf-8"?>. 
    

    为此,您需要一个带有 XDocument

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

    【讨论】:

      猜你喜欢
      • 2019-10-25
      • 2021-06-26
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2018-08-09
      相关资源
      最近更新 更多