1

我有一些看起来像..

<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();
4

1 回答 1

3

使用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());
于 2012-12-28T20:53:27.080 回答