简体   繁体   中英

Add An XML Declaration To String Of XML

I have some xml data that looks like..

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

I want to add "<?xml version=\\"1.0\\"?>" to this string. Then preserve the xml as a string.

I attempted a few things..

This breaks and loses the original xml string

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

This doesnt do anything, just keeps the original xml data with no declaration attached.

 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. The XmlWriter.Create accepts that setting (instead of the default contructor)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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