简体   繁体   English

我如何将一个属性序列化为具有默认属性的元素

[英]how can i serialize a property to element with a default attribute

I need to serialize this class with a property to xml, the property need to come as an element with the name of property as value for an default attribute. 我需要将具有属性的此类序列化为xml,该属性需要以元素的形式出现,并以属性名称作为默认属性的值。

 class RequestDto { public string ZipCode {get;set;} } as <RequestDto> <Parameter name="zipcode"> </Parameter> </RequestDto> 

You can't do that via XmlSerializer directly from the shape of that object model; 您不能直接从该对象模型的形状通过XmlSerializer basically, XmlSerializer assumes that your model and xml will be more or less the same. 基本上, XmlSerializer假设模型和XML将或多或少相同。 Implementing IXmlSerializable is frankly not worth it. 坦率地说,实现IXmlSerializable是不值得的。 I would suggest using XDocument to serialize that instead: 我建议使用XDocument来序列化它:

string zip = "abc";
var el = new XElement("RequestDto",
    new XElement("Parameter",
        new XAttribute("name", "zipcode"),
        zip
    )
);

Which gives (via .ToString() ): 给出(通过.ToString() ):

<RequestDto>
  <Parameter name="zipcode">abc</Parameter>
</RequestDto>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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