添加一个XML声明到XML字符串

本文关键字:XML 声明 字符串 一个 添加 | 更新日期: 2023-09-27 17:49:56

我有一些xml数据看起来像.

<Root>
<Data>Nack</Data>
<Data>Nelly</Data>
</Root>

我想把"<?xml version='"1.0'"?>"添加到这个字符串中。然后将xml保存为字符串。

我尝试了一些事情…

这将中断并丢失原始xml字符串

myOriginalXml="<?xml version='"1.0'"?>"  + myOriginalXml;

这没有做任何事情,只是保持原始的xml数据,没有附加声明。

 XmlDocument doc = new XmlDocument();
                doc.LoadXml(myOriginalXml);
                XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8","no");
                StringWriter sw = new StringWriter();
                XmlTextWriter tx = new XmlTextWriter(sw);
                doc.WriteTo(tx);
                string xmlString = sw.ToString();

这似乎也没有任何效果…

  XmlDocument doc = new XmlDocument();
                doc.LoadXml(myOriginalXml);
                XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
                MemoryStream xmlStream = new MemoryStream();
                doc.Save(xmlStream);
                xmlStream.Flush();
                xmlStream.Position = 0;
                doc.Load(xmlStream);
                StringWriter sw = new StringWriter();
                XmlTextWriter tx = new XmlTextWriter(sw);
                doc.WriteTo(tx);
                string xmlString = sw.ToString();

添加一个XML声明到XML字符串

使用xmlwritersettings来更好地控制保存。XmlWriter。Create接受该设置(而不是默认构造函数)

    var myOriginalXml = @"<Root>
                            <Data>Nack</Data>
                            <Data>Nelly</Data>
                          </Root>";
    var doc = new XmlDocument();
    doc.LoadXml(myOriginalXml);
    var ms = new MemoryStream();
    var tx = XmlWriter.Create(ms, 
                new XmlWriterSettings { 
                             OmitXmlDeclaration = false, 
                             ConformanceLevel= ConformanceLevel.Document,
                             Encoding = UTF8Encoding.UTF8 });
    doc.Save(tx);
    var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());