2
Answers

XML encoding issue

Ask a question
George George

George George

16y
2.4k
1

Hello everyone,


Here is my code, and it will always output UTF-16 at XML header even if I set the XML declaration to UTF-8.

Here is my code and output.

My questions,

1. How to make UTF-8 in header other than UTF-16?
2. Is the XML string really UTF-16 encoded or UTF-8 encoded? I think in C#, string is always UTF-16 encoded, why do we need a UTF-8 in header?

[Code]

<?xml version="1.0" encoding="utf-16"?>
<CategoryList a="12345" b="1d5458cd-a070-40cc-a3f4-cf3c394013cc" c="true" />

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

class Test
{
    public static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();


        // Write down the XML declaration
        XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

        // Create the root element
        XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
        xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
        // Set attribute name and value!
        rootNode.SetAttribute("a", "12345");
        rootNode.SetAttribute("b", Guid.NewGuid().ToString());
        rootNode.SetAttribute("c", "true");
        xmlDoc.AppendChild(rootNode);

        // Save to the XML file
        StringWriter stream = new StringWriter();
        xmlDoc.Save(stream);
        string content = stream.ToString();
        Console.Write(content);

        return;
    }
}
[/Code]


thanks in advance,
George


Answers (2)