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]
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
George GeorgePosted May 16, 2008, 7:29 AM
You load the file twice by invoking xmlDoc.Load(FileName), are there any ways to set encoding in XMLDocument? The constructor of XMLDocument looks like support to set encoding approach, like UTF-8.
Any ideas?
regards,
George
Blocked AccountPosted May 16, 2008, 6:29 AM
U can do that by using this code.
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter((FileName), System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("PageTitle");
xmlWriter.Close();
xmlDoc.Load(FileName);
XmlNode Root = xmlDoc.DocumentElement;
XmlElement Page = xmlDoc.CreateElement("Page");
Page.SetAttribute("ID", PageNumber.ToString());
XmlElement Id = xmlDoc.CreateElement("Id");
XmlElement Title = xmlDoc.CreateElement("Title");
XmlElement PageUrl = xmlDoc.CreateElement("PageUrl");
XmlText textId = xmlDoc.CreateTextNode("Hello");
XmlText textTitle = xmlDoc.CreateTextNode("Hello4");
XmlText textPageUrl = xmlDoc.CreateTextNode("Hello4");
textId.Value = PageNumber.ToString();
textTitle.Value = "PageTitle";
textPageUrl.Value = "WWW.c-sharpcorner.com";
Root.AppendChild(Page);
Page.AppendChild(Id);
Page.AppendChild(Title);
Page.AppendChild(PageUrl);
Id.AppendChild(textId);
Title.AppendChild(textTitle);
PageUrl.AppendChild(textPageUrl);
xmlDoc.Save(FileName);
Happy Coding!!