从Class中提取XmlRoot信息

时间:2017-05-15 17:54:15

标签: c# xml class xmlserializer

如何提取xmlSerializer.mapping(locked属性)以检索xmlroot elementname值,命名空间值和每个xmlattribute属性名?

ModelInfo mi = new ModelInfo {ModelName = "Andrea", ModelAge = 23};    
var xs = new XmlSerializer(mi.GetType()); 

[XmlRoot(ElementName = "Model", Namespace = "http://ws/")]
public class ModelInfo
{
    [XmlAttribute("name")]
    public string ModelName{ get; set; }

    [XmlAttribute("age")]
    public string ModelAge{ get; set; }
}

1 个答案:

答案 0 :(得分:0)

我认为无法从XmlSerializer实例中检索。

但你可以这样得到它:

ModelInfo mi = new ModelInfo { ModelName = "Andrea", ModelAge = 23 };

var xmlRoot = mi.GetType().GetCustomAttribute<XmlRootAttribute>();

if (xmlRoot != null)
{
    Console.WriteLine(xmlRoot.ElementName);
    Console.WriteLine(xmlRoot.Namespace);
}