views:

29

answers:

1
        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?

+5  A: 

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>
Jon Skeet