Impostazione InnerXml per XmlDocument provoca mancanza di fine-Tag
-
04-10-2019 - |
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?
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