设置与RootElement属性相同的元素名称

时间:2014-12-16 20:32:42

标签: c# generics xml-serialization

[XmlRootAttribute("ls")]
public class Request<T>
{
    [XmlAttribute("ver")]
    public string Version { get; set; }

    [XmlElement("hdr")]
    public Header Header { get; set; }
    [XmlElement(Type = typeof(class2), ElementName = "ChildClass")]
    public T Data { get; set; }
}


[XmlRoot("ChildClass")]
public class class2
{
    [XmlElement("login")]
    public string Property1{ get; set; }

}
[XmlRoot("ChildClass3")]
public class class3
{
    [XmlElement("User")]
    public string Property1{ get; set; }

}

序列化Request<class2>时,元素名称为&#34;数据&#34;。我希望元素名称为&#34; ChildClass&#34;。当序列化Request<class3>时,元素名称应为&#34; ChildClass3&#34;。 我怎么能这样做

1 个答案:

答案 0 :(得分:1)

据我所知,元素名称必须在编译时知道,因此您不能尝试使用Data对象XmlRoot或类名或类似名称,因为这些在编译时是未知的。您需要定义可以期望Data设置的每种可能类型。如下:

[XmlRoot("ls")]
public class Request
{
    [XmlAttribute("ver")]
    public string Version { get; set; }

    [XmlElement("ChildClass2",typeof(class2))]
    [XmlElement("ChildClass3",typeof(class3))]
    public object Data { get; set; }
}

public class class2
{
    [XmlElement("login")]
    public string Property1 { get; set; }
}

public class class3
{
    [XmlElement("User")]
    public string Property1 { get; set; }

}

以下两个对象:

var exampleObject = new Request
{
    Version = "versionExample",
    Data = new class2 { Property1 = "property1Example" }
};

var exampleObject2 = new Request
{
    Version = "versionExample",
    Data = new class3 { Property1 = "property1Example" }
};

然后序列化为:

<ls ver="versionExample">
  <ChildClass2>
    <login>property1Example</login>
  </ChildClass2>
</ls>
<ls ver="versionExample">
  <ChildClass3>
    <User>property1Example</User>
  </ChildClass3>
</ls>