ASP.NET MVC 3 XML Serialization: Serialize dash in

2019-06-02 12:05发布

问题:

Trulia's Dev Guide uses dashes in their element names. Assuming I create an object with similar names but with an underscore instead of a dash, would I need to create a custom XML serializer using XmlWriter to swap out the underscores with dashes or is there an easier way to do this? (something like .WriteElementString("street-address", myObject.street_address);

Sample XML:

<location>
    <street-address>1234 Lane</street-address>
    <city-name>Midway</city-name>
    <state-code>GA</state-code>
    <zipcode>31320</zipcode>
    <display-address>true</display-address>
</location>

回答1:

You can use attributes when serializing POCOs and deserializing XML, like the following:

[XmlElement("street-address")]
public string StreetAddress { get; set; }

[XmlElement("city-name")]
public string CityName { get; set; }