简体   繁体   English

将XML声明添加到XML字符串

[英]Add An XML Declaration To String Of XML

I have some xml data that looks like.. 我有一些看起来像的xml数据..

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

I want to add "<?xml version=\\"1.0\\"?>" to this string. 我想在此字符串中添加"<?xml version=\\"1.0\\"?>" Then preserve the xml as a string. 然后将xml保存为字符串。

I attempted a few things.. 我试了几件事......

This breaks and loses the original xml string 这会破坏并丢失原始的xml字符串

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

This doesnt do anything, just keeps the original xml data with no declaration attached. 这没有做任何事情,只保留原始的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();

This is also not seeming to have any effect.. 这似乎也没有任何影响..

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

Use an xmlwritersettings to achieve greater control over saving. 使用xmlwritersettings可以更好地控制保存。 The XmlWriter.Create accepts that setting (instead of the default contructor) 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM