为 XmlDocument 设置 InnerXml 会导致缺少结束标记

发布于 2024-09-24 11:36:36 字数 369 浏览 0 评论 0原文

        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateElement("Foo"));
        doc.DocumentElement.InnerXml = "Test";      
        StringBuilder result = new StringBuilder();
        doc.WriteContentTo(XmlWriter.Create(result));

最后的结果是:

<Foo>Test

表示缺少结束元素。这是为什么?我该如何解决它?

        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateElement("Foo"));
        doc.DocumentElement.InnerXml = "Test";      
        StringBuilder result = new StringBuilder();
        doc.WriteContentTo(XmlWriter.Create(result));

At the end, result is:

<Foo>Test

that means the end element is missing. Why is that and how can I fix it?

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

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

发布评论

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

评论(1

娇俏 2024-10-01 11:36:36

问题是您正在创建一个 XmlWriter,但没有处理它 - 所以它不会刷新。试试这个:

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

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateElement("Foo"));
        doc.DocumentElement.InnerXml = "Test";      
        StringBuilder result = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(result))
        {
            doc.WriteContentTo(writer);
        }
        Console.WriteLine(result);
    }
}

输出:

<?xml version="1.0" encoding="utf-16"?><Foo>Test</Foo>

The problem is that you're creating an XmlWriter, but not disposing of it - so it's not flushing. Try this:

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

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateElement("Foo"));
        doc.DocumentElement.InnerXml = "Test";      
        StringBuilder result = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(result))
        {
            doc.WriteContentTo(writer);
        }
        Console.WriteLine(result);
    }
}

Output:

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