Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern to populate an object with xml

I have an object to populate with xml. I think that I might use a contructor which accept this xml to build the object. But, is there a better design pattern to do it ? Is it to the object to handle all the xml parsing ?

Thank you !

like image 302
poiuytrez Avatar asked Nov 11 '10 23:11

poiuytrez


People also ask

Is XML a design pattern?

XML schemas contain numerous design patterns, the most common of which are Russian Doll, Salami Slice, Venetian Blind, and Garden of Eden. The patterns vary according to the number of their global elements or types. A global element or type, which is a child of the schema, contains a target namespace.

Which design pattern works on data?

Explanation: Command pattern is a data driven design pattern.

Which design pattern is used to access all elements in collections?

Iterator pattern lets us do just that. Formally it is defined as below: The iterator pattern provides a way to access the elements of an aggregate object without exposing its underlying representation.


3 Answers

No you should not send the xml to the constructor because you are coupling the model with deserilizing logic. You should create a class that handles the deserlization for you and return an instance. Why this is important might be unclear. But imagine in the future you may have the data coming from a database, you don't want to pass the database connection to the constructor, do you? Instead you can create a different class that uses databases to generate an instance of your class.

Here are some good read:

http://en.wikipedia.org/wiki/Builder_pattern

http://en.wikipedia.org/wiki/Immutable_object

like image 101
Amir Raminfar Avatar answered Oct 08 '22 17:10

Amir Raminfar


The simplest approach would be to let XmlSerializer do it for you. Just decorate it (if necessary) so that it knows how to map the xml, and call Deserialize.

like image 45
Marc Gravell Avatar answered Oct 08 '22 17:10

Marc Gravell


if you receive XML as a string which requires special parsing, you can, I guess, create a manager/factory to construct your object:

           var myObject = MyObjectCustomXmlSerializer.Deserialize(xmlString);
like image 30
dexter Avatar answered Oct 08 '22 18:10

dexter