开发者

Setting InnerXml for XmlDocument causes missing End-Tag

        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?


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜