views:

114

answers:

3

Hi,

I would like to find a better way to do this:

XmlNode nodeXML = xmlDoc.AppendChild( xmlDoc.CreateXmlDeclaration( "1.0", "utf-8", String.Empty) );

I do not want to think about "utf-8" vs "UTF-8" vs "UTF8" vs "utf8" as I type code. I would like to make my code less prone to typos. I am sure that some standard library has declatred "utf-8" as a const / readonly string. How can I find it? Also, what about "1.0"? I am assuming that major XML versions have been enumerated somewhere as well.

Thanks!

+2  A: 

You can use Encoding.UTF8 from System.Text.

JasCav
damn, beat me to it.
Neil N
Fastest fingers in the west... ;-)
JasCav
er... this doesn't appear to answer the question. Specifically, XMLDocument's CreateXmlDeclaration takes 3 strings. Encoding.UTF8 is returns an Encoding object. Furthermore, one must assume that CreateXMLDeclaration takes this string and creates a new Encoding object.
R. Bemrose
Well, to be entirely exact you need to access some property of that object, such as `WebName` http://msdn.microsoft.com/en-us/library/system.text.encoding.webname(v=VS.100).aspx
Matti Virkkunen
`Encoding.UTF8` by itself is not of type `string`. Which further property should I use? Bodyname? Encodingname? WebName? ToString()? Thanks.
Hamish Grubijan
+5  A: 

Try Encoding.UTF8.WebName.

Ben M
Thanks. What about "1.0" ? :)
Hamish Grubijan
static class ObsessiveCompulsive { public const string ONE_POINT_ZERO = "1.0"; } // There.
Matti Virkkunen
From wikipedia: "The second (XML 1.1) was initially published on February 4, 2004, the same day as XML 1.0 Third Edition[28], and is currently in its second edition, as published on August 16, 2006. It contains features (some contentious) that are intended to make XML easier to use in certain cases[29]. The main changes are to enable the use of line-ending characters used on EBCDIC platforms, and the use of scripts and characters absent from Unicode 3.2. XML 1.1 is not very widely implemented and is recommended for use only by those who need its unique features."
Ben M
+2  A: 

It is easy to avoid by using an XmlWriter to write the document. The default writer automatically encodes in utf8 and generates the processing instruction:

        var doc = new XmlDocument();
        doc.InnerXml = "<root></root>";
        using (var wrt = XmlWriter.Create(@"c:\temp\test.xml")) {
            doc.WriteTo(wrt);
        }

Output:

        <?xml version="1.0" encoding="utf-8"?><root></root>
Hans Passant
Thanks, I do, however, want to have it in the code, so that there are no questions about what the encoding is regardless of the library used. Some apps are less sensitive to encodings than others.
Hamish Grubijan
It *is in the code*. Everybody knows what XmlWriter.Create() does.
Hans Passant