[英]DataContractSerializer - How to serialize objects using ElementName instead of property name?
I'm facing serialization issue while using DataContractSerializer
. 使用
DataContractSerializer
遇到序列化问题。 The issue I'm facing is that the generated XML file always have the tags with names defined for the class and fields instead of the names set in XmlRoot
or XmlElement
using ElementName
attribute. 我面临的问题是,生成的XML文件始终具有为类和字段定义名称的标签,而不是使用
ElementName
属性在XmlRoot
或XmlElement
设置的名称。 eg For the class defined as follows: 例如,对于定义如下的类:
[XmlRoot(ElementName = "customer")]
public class Customer
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "address")]
public string Address { get; set; }
}
The generated XML in my case is always: 在我的情况下,生成的XML始终是:
<Customer>
<Name>abc</Name>
<Address>xyz</Address>
</Customer>
while the output I'm looking to get is the one using ElementName
in lowercase: 而我想要获得的输出是使用
ElementName
小写的输出:
<customer>
<name>abc</name>
<address>xyz</address>
</customer>
I'm using an extension method to serialize by C# object using the following: 我使用扩展方法通过C#对象使用以下方法进行序列化:
public static XDocument SerializeToXElement(object o)
{
XDocument doc = new XDocument();
using (var writer = doc.CreateWriter())
{
var serializer = new DataContractSerializer(o.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.WriteObject(writer, o);
}
doc.StripNamespace();
return doc;
}
I also have another extension method being called in my serialize function to strip the namespaces out from my XDocument
, which is as follows: 我的序列化函数中还调用了另一个扩展方法,以将命名空间从
XDocument
剥离出来,如下所示:
public static void StripNamespace(this XDocument document)
{
if (document.Root == null) return;
foreach (var element in document.Root.DescendantsAndSelf())
{
element.Name = element.Name.LocalName;
element.ReplaceAttributes(GetAttributesWithoutNamespace(element));
}
}
What can I do to make the DataContractSerializer use ElementName
instead of the class/property names? 如何使DataContractSerializer使用
ElementName
而不是类/属性名称?
This should work for you, 这应该为您工作,
[XmlRoot("customer")]
public class Customer
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("address")]
public string Address { get; set; }
}
As per my comment, you should use DataContract and DataMember attributes instead of XmlRoot
and XmlElement
: 根据我的评论,您应该使用DataContract和DataMember属性而不是
XmlRoot
和XmlElement
:
[DataContract(Name = "customer", Namespace = "")]
public class Customer
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "address")]
public string Address { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.