为XmlDocument设置InnerXml会导​​致缺少End-Tag

时间:2010-09-21 13:50:11

标签: c# .net xml xmldocument innerxml

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

最后,结果是:

<Foo>Test

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

1 个答案:

答案 0 :(得分: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>