【问题标题】:How to get XML with header (<?xml version="1.0"...)?如何获取带有标头的 XML (<?xml version="1.0"...)?
【发布时间】:2019-06-02 15:41:04
【问题描述】:

考虑以下创建 XML 文档并显示它的简单代码。

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
XmlComment comment = xml.CreateComment("Comment");
root.AppendChild(comment);
textBox1.Text = xml.OuterXml;

它按预期显示:

<root><!--Comment--></root>

但是,它不显示

<?xml version="1.0" encoding="UTF-8"?>   

那么我怎样才能得到它呢?

【问题讨论】:

    标签: c# .net xml xmldocument


    【解决方案1】:

    使用XmlDocument.CreateXmlDeclaration Method 创建一个 XML 声明:

    XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
    xml.AppendChild(docNode);
    

    注意:方法请看文档,尤其是encoding参数:对这个参数的取值有特殊要求。

    【讨论】:

    • 谢谢。我以为那是自动的。
    • +1。请注意,期望“Utf-8”与字符串编码不匹配(请参阅 +1 Nicholas Carey 回答)。
    • @AlexeiLevenkov 谢谢。但我OuterXmling 并使用它。还是我错过了什么,即使那样也有问题?
    • @ispiro string s = "&lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;root/&gt;" 在某种程度上是一个谎言(string 在 C#/.Net 中的编码不是 UTF8)。根据您的其余代码/使用情况,它可能会或可能不会有问题(即,如果您将其保存为 UTF16 失败,那么您就有麻烦了)。
    【解决方案2】:

    您需要使用 XmlWriter(默认情况下写入 XML 声明)。您应该注意 C# 字符串是 UTF-16 并且您的 XML 声明表明该文档是 UTF-8 编码的。这种差异可能会导致问题。下面是一个示例,写入一个给出您期望结果的文件:

    XmlDocument xml = new XmlDocument();
    XmlElement root = xml.CreateElement("root");
    xml.AppendChild(root);
    XmlComment comment = xml.CreateComment("Comment");
    root.AppendChild(comment);
    
    XmlWriterSettings settings = new XmlWriterSettings
    {
      Encoding           = Encoding.UTF8,
      ConformanceLevel   = ConformanceLevel.Document,
      OmitXmlDeclaration = false,
      CloseOutput        = true,
      Indent             = true,
      IndentChars        = "  ",
      NewLineHandling    = NewLineHandling.Replace
    };
    
    using ( StreamWriter sw = File.CreateText("output.xml") )
    using ( XmlWriter writer = XmlWriter.Create(sw,settings))
    {
      xml.WriteContentTo(writer);
      writer.Close() ;
    }
    
    string document = File.ReadAllText( "output.xml") ;
    

    【讨论】:

    • 如何使用此代码设置列宽,我可以在 ASP.NET MVC 中使用它吗?
    【解决方案3】:
    XmlDeclaration xmldecl;
    xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
    
    XmlElement root = xmlDocument.DocumentElement;
    xmlDocument.InsertBefore(xmldecl, root);
    

    【讨论】:

    • 谢谢。 InsertBefore 看起来很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2015-07-15
    • 2018-01-04
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多