I am facing issue in serialization of XmlDocument when XmlSerializer is instantiated with XmlRootAttribute. This is the sample that I have prepared to reproduce the issue.
class Program
{
static void Main(string[] args)
{
SerializeDataSet("a1.xml");
}
private static void SerializeDataSet(string filename)
{
XmlDocument testProperties = new XmlDocument();
XmlSerializer ser = new XmlSerializer(typeof(XmlDocument), null, new Type[0], new XmlRootAttribute("dummy"), "testns");
// Creates a DataSet; adds a table, column, and ten rows.
DataSet ds = new DataSet("mydatads");
DataTable t = new DataTable("mytable1");
DataColumn c = new DataColumn("mycolumn");
t.Columns.Add(c);
ds.Tables.Add(t);
DataRow r;
for (int i = 0; i < 10; i++)
{
r = t.NewRow();
r[0] = "row " + i;
t.Rows.Add(r);
}
testProperties.LoadXml(ds.GetXml());
TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, testProperties);
writer.Close();
}
}
This is failing with following exception.
Unhandled exception. System.InvalidOperationException: There was an error generating the XML document.
---> System.InvalidOperationException: This element was named 'mydatads' from namespace '' but should have been named 'dummy' from namespace ''.
at System.Xml.Serialization.XmlSerializationWriter.WriteElement(XmlNode node, String name, String ns, Boolean isNullable, Boolean any)
at System.Xml.Serialization.XmlSerializationWriter.WriteElementLiteral(XmlNode node, String name, String ns, Boolean isNullable, Boolean any)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterXmlDocument.Write1_dummy(Object o)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
at Program.SerializeDataSet(String filename) in Program.cs:line 49
at Program.Main(String[] args) in Program.cs:line 26
When I create instance of XmlSerializer
as new XmlSerializer(typeof(XmlDocument));
then it works but then
it misses the root element. Other than that, I don't have control over it. I can change XmlDocument
but can't change XmlSerializer
.
I am not sure what is going wrong when XmlRootAttribute
is present.