Configuración InnerXml para XmlDocument provoca falta End-Tag
-
04-10-2019 - |
Pregunta
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateElement("Foo"));
doc.DocumentElement.InnerXml = "Test";
StringBuilder result = new StringBuilder();
doc.WriteContentTo(XmlWriter.Create(result));
Al final, resultado es:
<Foo>Test
que significa que el elemento extremo se encuentra. ¿Por qué es y cómo puedo solucionarlo?
Solución
El problema es que se está creando un XmlWriter, pero no disponer de él - así que no es el lavado. Prueba esto:
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);
}
}
Salida:
<?xml version="1.0" encoding="utf-16"?><Foo>Test</Foo>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow