Laurin
Laurin

Reputation: 13

Transform XML File into a Domain Model

I get an xml file with a lot of data from another software system. I have to do a lot of work with this data, so i would like to transform this xml data into a specific domain model, which allows me to work more efficient. So i need a mechanism to map the xml data to the domain model and vice versa. What are my possibilities, can you complete the list?

Thank you in advance, best regards :-) Laurin

Edit: Simply said: I want to do OR Mapping but instead of an DBMS i have an XML file ;-)

Upvotes: 1

Views: 2166

Answers (3)

Anuraj
Anuraj

Reputation: 19598

XML Serialization / De-Serialization seems a good idea, if you have a domain object available.

More info about XmlSerializer Class

Upvotes: 0

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

try to use Linq to Xml. Your mapper will be looks like following code.

xml:

<contacts>
  <contact contactId="2">
     <firstName>Barry</firstName>
     <lastName>Gottshall</lastName>
  </contact>
  <contact contactId="3">
     <firstName>Armando</firstName>
     <lastName>Valdes</lastName>
  </contact>
</contacts>

code for load data:

XDocument loaded = XDocument.Load(@"C:\contacts.xml");

mapping:

List<MyContact> contacts = (from c in loaded.Descendants("contact")
    select new MyContacts() {
                                 FirstName = (string)c.Element("firstName"),
                                 LastName = (string)c.Element("lastName")
                             }).ToList();

Upvotes: 3

detaylor
detaylor

Reputation: 7280

You could also implement System.Xml.Serialization.IXmlSerializable assuming that there is a one to one relationship between xml models and your objects. There is more information at Proper way to implement IXmlSerializable?

Upvotes: 0

Related Questions