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 !
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:
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.
如果您将XML作为需要特殊解析的字符串接收,我猜,您可以创建一个管理器/工厂来构建您的对象:
var myObject = MyObjectCustomXmlSerializer.Deserialize(xmlString);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.