Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UTF-8 in Uppercase using XDocument

I need to have XML encoding and version at the top of my XML document which I am making with XDocument.

I have this but it is in lowercase, and it needs to be in uppercase.

What do I need to do?

I declare a new XML document using the XDocument class called 'doc'.

I save this to a file using doc.Save();.

I have tried:

  • doc.Declaration.Encoding.ToUpper();
  • Declaring a new XDeclaration
  • Typing the Encoding in uppercase and setting my doc.Declaration to my XDeclaration.

It still comes through in lowercase.

like image 791
JMK Avatar asked Dec 17 '11 20:12

JMK


2 Answers

You can create custom XmlTextWriter, e.g.:

public class CustomXmlTextWriter : XmlTextWriter
{
    public CustomXmlTextWriter(string filename)
        : base(filename, Encoding.UTF8)
    {

    }

    public override void WriteStartDocument()
    {
        WriteRaw("<?xml VERSION=\"1.0\" ENCODING=\"UTF-8\"?>");
    }

    public override void WriteEndDocument()
    {
    }
}

Then use it:

using (var writer = new CustomXmlTextWriter("file.xml"))
{
    doc.Save(writer);
}
like image 81
Kirill Polishchuk Avatar answered Nov 19 '22 19:11

Kirill Polishchuk


Working solution, using XmlDocument:

 myXmldoc.FirstChild.Value = "version=\"1.0\" encoding=\"UTF-8\""; 

As user726720 pointed out, the answer give by Kirill Polishchuk losses the formatting and requires mode code.

like image 1
ana boies Avatar answered Nov 19 '22 19:11

ana boies