tags:

views:

1609

answers:

4

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

Thanks,
rAyt

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>
    ...
A: 

Use xml.OuterXml.toString();

Jeff
Does XDocument contain an OuterXml property? I thought that was only XmlDocument. MSDN indicates it doesn't have that property.
Ryan Brunner
Jap, XDocument doesn't have OuterXml but the Declaration property
Henrik P. Hessel
Woops, misread that.
Jeff
+5  A: 

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()
Ryan Brunner
it seems if you don't use new XDeclaration("1.0", "utf-8", "yes") in your xdocument this creates an error because xml.Declaration is null. But xml.save seems to autodetect the right encoding.
Henrik P. Hessel
A: 

You can also use an XmlWriter and call the

Writer.WriteDocType()

method.

Gus Paul
+13  A: 

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();
Jon Skeet
This has a small issue in that the encoding in the XDocument declaration is ignored and replaced by the encoding of the StringWriter when doing the save, which may or may not be what you want
Sam Holder