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

这意味着缺少结束元素。为什么会这样,我该如何解决?

4

1 回答 1

6

问题是您正在创建一个 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>
于 2010-09-21T13:54:19.560 回答