Question

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

A la fin, le résultat est:

<Foo>Test

signifie que l'élément d'extrémité est manquante. Pourquoi est-ce et comment puis-je résoudre ce problème?

Était-ce utile?

La solution

Le problème est que vous créez un XmlWriter, mais pas en disposer - donc il ne chasse d'eau. Essayez ceci:

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);
    }
}

Sortie:

<?xml version="1.0" encoding="utf-16"?><Foo>Test</Foo>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top