开发者

Transform XML File into a Domain Model

开发者 https://www.devze.com 2023-02-21 21:52 出处:网络
I get an xml file with a lot of data from another software system. I have to do a lot of work with t开发者_开发技巧his data, so i would like to transform this xml data into a specific domain model, wh

I get an xml file with a lot of data from another software system. I have to do a lot of work with t开发者_开发技巧his 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?

  • Linq to XSD
  • Manual mapping over linq to xml oder xml DOM
  • DataSets (Read/Write XML) !?
  • ...?

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 ;-)


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();


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?


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

More info about XmlSerializer Class

0

精彩评论

暂无评论...
验证码 换一张
取 消