XML Deserialization Question

X

xlar54

Lets say I have an xml document that reads:

<Book>
<ID>
<Title>SomeTitle</Title>
<ISBN>12345</ISBN>
</ID>
</Book>

But I want to deserialize it to an object that looks like:

[XmlRoot("Book")]
public class Book
{
[XmlElement(ElementName="Title")]
public string Title;

[XmlElement(ElementName="ISBN"])
public string isbn;
}

The problem appears to be the ID element in the xml document. How do
I qualify the XmlElement attributes so that the Title goes into the
Title, and ISBN goes into ISBN? Should it be something like
[XmlElement(ElementName="ID.Title")] ?
 
N

Nicholas Paldino [.NET/C# MVP]

If you are going to do this with attributes on your class, then you will
have to expose a structure with the title and ISBN through a property named
ID (or something else, if you apply the XmlElement attribute to it).

Otherwise, you have to implement IXmlSerializable, and serialize this in
a custom manner. I would create a private structure with the title and ISBN
codes in it, and then attach the xml serialization attributes to that. In
your implementation of IXmlSerializable, you would then navigate to the ID
tag, and deserialize an instance of the private structure from there.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

in message
news:[email protected]...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top