Let’s say I have an XML file such as this:
<root>
<level1 name="level1A">
<level2 name="level2A">
<level3 name="level3A">
<level4 name="level4A">
<level5 name="level5A">
<level6 name="level6A">
<level7 name="level7A">
<level8 name="level8A"></level8>
</level7>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
<level1 name="level1B">
<level2 name="level2B">
<level3 name="level3B">
<level4 name="level4B">
<level5 name="level5B">
<level6 name="level6B">
<level7 name="level7B">
<level8 name="level8B"></level8>
</level7>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
</root>
How can I read this file and execute a code snippet depending on the element? for example, if the “name” element says “level7a”, execute code snippet X. If the name element says level7B, execute code snippet Y.
I can provide such code snippets if t makes answering the question easier. Thanks for the help!
You could create a
Dictionary<string, Action>which maps attribute names to actions. Then while parsing the xml you can look up the snippet in the dictionary and execute it.Quick example:
You would need to check that the key actually exists but you could make extension method for that to encapsulate that functionality:
Then you can call it like this:
Instead of an
Action(which is a parameterless snippet returningvoid) you might want to useAction<T>orFunc<T, R>in case you need to pass paramters and/or get return values.