Nick LaMarca
Nick LaMarca

Reputation: 8188

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

Upvotes: 1

Views: 11152

Answers (1)

rene
rene

Reputation: 42414

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

Upvotes: 3

Related Questions