[英]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. 我试图将一个类序列化为XML,并将属性序列化为该类的属性,而不是嵌套节点。 I am using WebApi to automatically handle the serialization of the XML.
我正在使用WebApi自动处理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]
): 这是我收到的输出(请注意,尽管
Property1
尽管用[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. 我不熟悉WebApi,但是您收到的输出看起来像是使用
DataContractSerializer
而不是您需要的XmlSerializer
进行了序列化。 Check if adding the following to Application_Start
in Global.asax
helps: 检查将以下内容添加到
Global.asax
Application_Start
有帮助:
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 ) (摘自http://serena-yeoh.blogspot.de/2013/02/xml-serialization-in-aspnet-web-api.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.