Microsoft.AspNet.Mvc.Formatters.Xml 忽略了 XmlElement 属性

XmlElement Attribute being ignored by Microsoft.AspNet.Mvc.Formatters.Xml

我在 asp.net 5 控制器中返回一个对象作为 xml。该对象有一个 属性 列表,我需要序列化程序忽略列表的根元素。我遵循了这个 post 的建议 Use XML serialization to serialize a collection without the parent node 但由于某种原因它不起作用它甚至忽略了如果我尝试使用 [XmlElement("newName") 更改它的名称]

它为什么会这样做的任何线索?

public partial class Doc {

    [XmlElement("Detalle")]
    public List<DefTypeDetalle> Detalle { get; set; }

}

public partial class DefTypeDetalle {

    public Id { get; set; }
}

我得到的输出

<Doc>
    <Detalle>
        <DefTypeDetalle>
            <Id>1<Id/>
        </DefTypeDetalle>
        <DefTypeDetalle>
            <Id>2<Id/>
        </DefTypeDetalle>
    </Detalle>
</Doc>

而我想要的是

<Doc>   
    <Detalle>
        <Id>1<Id/>
    </Detalle>
    <Detalle>
        <Id>2<Id/>
    </Detalle>  
</Doc>

谢谢

这可能是您序列化数据的方式。尝试

XmlSerializer serializer = new XmlSerializer(typeof(List<DefTypeDetalle>));
    using ( TextWriter writer = new StreamWriter( @"your_directory")
    {
        serializer.Serialize(writer, your_list) 
    }  

所以问题出在我使用的格式化程序上,我在 Startup.cs

 mvcBuilder.AddXmlDataContractSerializerFormatters();

并且需要使用 xml 序列化器

mvcBuilder.AddXmlSerializerFormatters();