简体   繁体   中英

Standard way to instantiate objects from an xml config file

QUESTION: How can I instantiate a model based on a config file?

BACKGROUND: I have a model simulator application consisting of dozens of different types of objects, each composed of other objects (in a complex compositional hierarchy). I would like to be able to instantiate the model based on an external configuration file. Is there a "standard approach" for this sort of task?

So for example, if I had a config.xml file like this:

<site>
    <facility name="F1">
        <tank name="t1"/>
        <pipe name="p1"/>
    </facility>
    <facility name="F2">
    ...

I want a Configurator that can parse that file and create a Site object composed of a collection of Facility objects composed of various Tank & Pipe equipment, etc. (Eventually I will also do this in reverse to persist the model.) The model configuration will change frequently; users will collect many different versions of the config file.

Here are some options I've seen suggested, but I haven't used any of these tools much yet, and I'm hoping to get some advice as to which (if any) of these approaches might be most appropriate for this problem.

  1. Role my own xml config file, parse it using XmlTextReader, and instantiate the model using reflection to map strings to types. (But is this re-inventing the wheel?)
  2. Use ConfigurationManager from System.Configuration , storing settings in app.config. (But not sure how to support the "many different versions of the config file" requirement.)
  3. Use XmlSerializer. (But I understand this requires default constructors, which would rule out constructor-based Dependency Injection which I had hoped to use.)
  4. Use an IoC Container. (But I have several inexperienced programmers who will be interacting with the program; I'd rather not overwhelm them with unnecessary complexity.)

(Bottom line: I hope to "do the simplest thing that could possibly work". But my unfamiliarity with these tools prevents me from determining which one is simplest.)

Option 1:

@JohnSaunders says that a specific way to create a XmlTextReader is deprecated, not XmlTextReader per se. That's true. See here: http://msdn.microsoft.com/en-us/library/9khb6435(v=vs.110).aspx

While a long list of cases is one option, one would probably not create such a knot in the code. Alternatives:

Option 2:

I can't see how saving the configuration in app.config instead of some other XML file relates to or solves your original problem.

Option 3:

Then don't scatter the serialization code.

Option 4:

How about looking into the source code of a not so big DI Framework to get ideas how to do it then?

HTH

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM