简体   繁体   中英

Property will not serialize as XML attribute

I am attempting to serialize a class as XML and to have the properties be serialized as attributes of the class, rather than a nested node. I am using WebApi to automatically handle the serialization of the XML.

This is my class:

[DataContract (Namespace="", Name="AttributeTest")]
[Serializable]
public class AttributeTestClass
{
    [XmlAttribute("Property")]
    [DataMember]
    public int Property1 { get; set; }
}

Here is the output I am receiving (note that Property1 is not an attribute in spite of it being decorated with [XmlAttribute] ):

<AttributeTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Property1>123</Property1>
</AttributeTest>

This is the output I want to receive:

<AttributeTest Property1="123" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
</AttributeTest>

What am I missing?

I'm not familiar with WebApi but the output you receive looks like it's serialized using DataContractSerializer , not XmlSerializer which you would need. Check if adding the following to Application_Start in Global.asax helps:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(
    new System.Net.Http.Formatting.XmlMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

(From http://serena-yeoh.blogspot.de/2013/02/xml-serialization-in-aspnet-web-api.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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