Pregunta

I'm using C#/.NET to deserialize a XML file that looks akin to this:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book
    Title="Animal Farm"
    PublishedDate="08/17/1945"
    />
  ... More Book nodes ...
</Books>

My classes, for the deserialized XML, look like:

[XmlRoot("Books")]
public class BookList
{
    // Other code removed for compactness. 

    [XmlElement("Book")]
    public List<Book> Books { get; set; }
}

public class Book
{
    // Other code removed for compactness. 

    [XmlAttribute("Title")]
    public string Title { get; set; }

    [XmlAttribute("PublishedDate")]
    public string PublishedDate { get; set; }

    public string Month { get; set; }

    public string Year { get; set; }
}  

When deserializing, I want to store the Book's PublishedDate attribute value in a Book object's PublishedDate property. However, I also want to parse the PublishedDate and assign its Month and Year to those properties.

Is there a way to parse the PublishedDate property, and populate the Month and Year properties, while deserialization occurs (without using a backing field)? For instance, is there an interface that provides a method for post-processing a deserialized node? Is there a XmlSerializer event that fires each time a known object is deserialized? Something else along these lines?

Note that I realize the no backing field requirement is arbitrary; I'm just curious to learn if there are other options.

¿Fue útil?

Solución

@Ondrej-Janacek 's anwser is the way to go. Just to fulfill your curiosity you could potentially remove the XmlAttribute from the PublishDate property and add another one like so

[XmlAnyAttribute]
public XmlAttribute[]XAttributes {get; set;}

This property will be called with all attributes found in the XML that don't correspond to any member. Inside it's setter you can lookup the PublishDate value and assign the values to your PublishDate, Month and Year properties. Without any backing field.

See here for more info on the XmlAnyAttribute.

Otros consejos

Well, one workaround would be

public string Month 
{ 
    get 
    { 
        return DateTime.Parse(PublishedDate).Month; 
    }
    set
    {       
        PublishedDate = ... // this would be a little more code, but you can also do it
    }
}

Year would be pretty similar.

As for that event, only events that the XmlSerializer class provides are

UnknownAttribute, UnknownElement, UnknownNode and UnreferencedObject. I guess you would have to create your own XmlSerializer, which is, by the way, not that much of a work.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top