使用 XDocument 获取大写的 UTF-8

发布于 2024-12-21 20:46:22 字数 432 浏览 4 评论 0原文

我需要在使用 XDocument 制作的 XML 文档的顶部添加 XML 编码和版本。

我有这个,但它是小写的,并且需要是大写的。

我需要做什么?

我使用名为“doc”的 XDocument 类声明一个新的 XML 文档。

我使用 doc.Save(); 将其保存到文件中。

我尝试过:

  • doc.Declaration.Encoding.ToUpper();
  • 声明一个新的 XDeclaration
  • 以大写形式键入编码并设置我的 doc.Declaration到我的 XDeclaration

它仍然以小写形式出现。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅笑轻吟梦一曲 2024-12-28 20:46:22

您可以创建自定义 XmlTextWriter,例如:

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()
    {
    }
}

然后使用它:

using (var writer = new CustomXmlTextWriter("file.xml"))
{
    doc.Save(writer);
}

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);
}
春庭雪 2024-12-28 20:46:22

使用 XmlDocument 的工作解决方案:

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

正如 user726720 指出的那样,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文