1

So in my C# program, I am reading in a series of commands that a user wants this program to perform from a file. I am currently using XML to store this data.

I am having a hard time thinking of a good way to store this data without littering the code with XML data access calls, and thus coupling this to using XML only.

Here is an example of the kind of XML I'm using (to give context):

<cooking>
    <job>
      <name>Cook Scrambled Eggs</name>
      <device>Robo-Chef</device>
      <action>
        <name>break eggs into pan</name>
      </action>
      <action>
        <name>scramble the eggs</name>
        <duration> 00:01:00</duration>
      </action>
    </job>    

    <trigger>
      <name>Breakfast</name>
      <forJob>Cook Scrambled Eggs</forJob>
      <start_time> Everyday at 7:00 AM</start_time>
    </trigger>    
</cooking>

What is a good way to read and store this data in my program from the scheduling XML file, such that the rest of the program is decoupled from the fact it was from an XML file?

Xantham
  • 1,829
  • 7
  • 24
  • 42
  • Could somebody explain the downvotes? How is this not a real question? I am asking how to read an XML in a decoupled fashion. This kind of behavior is rather discouraging to a beginner in something (in this case XML). – Xantham Dec 08 '12 at 01:59

1 Answers1

1

Well, you could actually serialize and de-serialize to C# objects.

In that case, you would need to extract an XML Schema from your sample data, use xsd.exe to generate your C# classes, and then serialize and deserialize using the XmlSerializer.

Generating a schema and classes: https://stackoverflow.com/a/11654672/1373170

That way you'd only couple to other C# classes, not worrying about the source. You could even later change your format to JSON for example, without having to refactor everything.

Community
  • 1
  • 1
Pablo Romeo
  • 11,298
  • 2
  • 30
  • 58
  • Thank you very much for the answer. I did not even know this existed, that is exactly what I wanted. – Xantham Dec 08 '12 at 01:54
  • 1
    Sure thing. I also just found this similar answer that provides an example of how to use the XmlSerializer: http://stackoverflow.com/a/364410/1373170 – Pablo Romeo Dec 08 '12 at 01:56