我有一些看起来像..
<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();