Domanda

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

Alla fine, risultato è:

<Foo>Test

che significa che l'elemento di estremità è mancante. Perché è questo e come posso risolvere il problema?

È stato utile?

Soluzione

Il problema è che si sta creando un XmlWriter, ma non disponendo di esso - quindi non è vampate di calore. Prova questo:

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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top