简体   繁体   English

使用XDocument序列化时更改根元素的名称

[英]Change name of root element when serializing with XDocument

I try to change the root name when serializing to XDocument. 我尝试在序列化为XDocument时更改根名称。

I try to serialize a(n inner) class and get the root name Test.MyClass . 我尝试序列化一个(n内部)类,并获得根名称Test.MyClass
I try to change it with XmlRoot attribute but nothing happens. 我尝试使用XmlRoot属性更改它,但没有任何反应。 What is the trick to change the root name? 更改根名称的诀窍是什么? or am I using XDocument for something it cannot do? 还是我将XDocument用于它无法完成的事情?

[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/>

As noted in the documentation you need to use the DataContract or Serializable attribute on the class you're going to use DataContractSerializer on. 文档所述,您需要在将要使用DataContractSerializer的类上使用DataContractSerializable属性。 The XmlRoot attribute is for use with the XmlSerializer , as noted by @ jdweng in their comment . XmlRoot属性用于XmlSerializer ,正如@jdweng其注释中指出的那样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM