tags:

views:

16

answers:

2

Forenote: When I refer to 'interfaces' here, I mean the actual interface to an object, not interface classes, i.e. class Customer { public Name {get;set;} } includes a Name property in its interface.

Is there a pattern for exposing XML element values as class interface properties, e.g. with the following XML:

<Notification name="RequestCreated">
  <Email address="[email protected]">
    Hello there, blah blah.
  </Email>
</Notification>

I would have a Notification interface with properties called Name and EmailAddress that would return RequestCreated and [email protected] respectively. It seems clumsy to use an XmlDocument instance and XPath for each interface property, so I'm hoping there is some sort of mapping mechanism I can use.

A: 

Well, if you're already mapping them to and from .xml files, why not just use XmlSerializer to serialize/deserialize the data directly into objects?

AllenG
XmlSerializer doesn't work with interfaces
Thomas Levesque
@Thomas Levesque: true, he'd need to instanciate a class to use XmlSerializer.
AllenG
@Thomas, please see my Forenote edit regarding interfaces.
ProfK
+1  A: 

I tend to use either of two methods when mapping XML to objects:

Linq to XML

When MS released the Linq to XML API, with XDocument and its extensions, I said goodbye to XmlDocument forever. You could extract content into POCO's with a simple query like this:

var doc = XDocument.Load(@".\temp.xml");
var query = from elem in doc.Descendants("Email")
            select new
            {
                Address = elem.Attribute("address").Value,
                Message = elem.Value.Trim()
            };

Xsd.exe

For some time, MS provided a schema and class generator for XML files. Xsd.exe can be used to infer an XML schema based on an XML file, and then generate classes based on the schema. The classes can serialize/deserialize XML using the .NET XmlSerializer. Here's an example (but take a look at xsd.exe /? for a list of options):

rem Create the schema, temp.xsd
xsd temp.xml
rem Create the serializable classes
xsd temp.xsd /classes /namespace:Demo

If you choose, you could go retro-fit the generated class to use interfaces.

kbrimington
Thanks @kbrimington, I think xsd.exe is probably what I will use. Please see my Forenote edit regarding interfaces.
ProfK