Get UTF-8 in Uppercase using XDocument

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-09 16:41:03

问题


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.


回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/8547675/get-utf-8-in-uppercase-using-xdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!