XDocument.ToString() drops XML Encoding Tag

Viewed 53231

Is there any way to get the xml encoding in the toString() Function?

Example:

xml.Save("myfile.xml");

leads to

<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>

But

tb_output.Text = xml.toString();

leads to an output like this

<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>
    ...
9 Answers

Either explicitly write out the declaration, or use a StringWriter and call Save():

using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = @"<?xml version='1.0' encoding='utf-8'?>
<Cooperations>
  <Cooperation />
</Cooperations>";

        XDocument doc = XDocument.Parse(xml);
        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new StringWriter(builder))
        {
            doc.Save(writer);
        }
        Console.WriteLine(builder);
    }
}

You could easily add that as an extension method:

public static string ToStringWithDeclaration(this XDocument doc)
{
    if (doc == null)
    {
        throw new ArgumentNullException("doc");
    }
    StringBuilder builder = new StringBuilder();
    using (TextWriter writer = new StringWriter(builder))
    {
        doc.Save(writer);
    }
    return builder.ToString();
}

This has the advantage that it won't go bang if there isn't a declaration :)

Then you can use:

string x = doc.ToStringWithDeclaration();

Note that that will use utf-16 as the encoding, because that's the implicit encoding in StringWriter. You can influence that yourself though by creating a subclass of StringWriter, e.g. to always use UTF-8.

The Declaration property will contain the XML declaration. To get the contents plus declaration, you can do the following:

tb_output.Text = xml.Declaration.ToString() + xml.ToString()

You can also use an XmlWriter and call the

Writer.WriteDocType() 

method.

string uploadCode = "UploadCode";
string LabName = "LabName";
XElement root = new XElement("TestLabs");
foreach (var item in returnList)
{  
       root.Add(new XElement("TestLab",
                new XElement(uploadCode, item.UploadCode),
                new XElement(LabName, item.LabName)
                            )
               );
}

XDocument returnXML = new XDocument(new XDeclaration("1.0", "UTF-8","yes"),
             root);

string returnVal;
using (var sw = new MemoryStream())
{
       using (var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
       {
              returnXML.Save(strw);
              returnVal = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
       }
}

// ReturnVal has the string with XML data with XML declaration tag

Extension method to get the Xml Declaration included, using string interpolation here and chose to add a new line after xml declaration as this is the standard I guess.

public static class XDocumentExtensions {
        
public static string ToStringIncludeXmlDeclaration(this XDocument doc){
               return $"({((doc.Declaration != null ? doc.Declaration.ToString() + 
     Environment.NewLine : string.Empty) + doc.ToString())}";
    }  
  }
}

Usage:

tb_output.Text = xml.ToStringIncludeXmlDeclaration();
Related