Reputation: 7702
I try to change the root name when serializing to XDocument.
I try to serialize a(n inner) class and get the root name Test.MyClass
.
I try to change it with XmlRoot
attribute but nothing happens. What is the trick to change the root name? or am I using XDocument for something it cannot do?
[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
var res = Serialise(new MyClass());
}
private static XDocument Serialise(object objectToSerialize)
{
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
var serializer = new DataContractSerializer(objectToSerialize.GetType());
serializer.WriteObject(writer, objectToSerialize);
}
return doc;
}
[XmlRoot("NewName")]
public class MyClass { }
}
I get
<MyTestClass.MyClass/>
but I want
<NewName/>
Upvotes: 0
Views: 158
Reputation: 12115
As noted in the documentation you need to use the DataContract
or Serializable
attribute on the class you're going to use DataContractSerializer
on. The XmlRoot
attribute is for use with the XmlSerializer
, as noted by @jdweng in their comment.
Upvotes: 1