读取XML和执行动作取决于属性属性、动作、XML

2023-09-04 10:05:41 作者:冷风中独走

比方说,我有一个XML文件,像这样的:

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>

我怎样才能读取这个文件并执行取决于元素在code段?例如,如果name元素说level7a,执行code段X.如果名称元素说level7B,执行code段年。

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.

我可以提供这样的code片段,如果T使得回答这个问题更容易。感谢您的帮助!

I can provide such code snippets if t makes answering the question easier. Thanks for the help!

推荐答案

您可以创建一个词典&LT;字符串,作用&gt; 这映射属性名称的行为。然后在解析XML就可以查找片段在字典中并执行它。

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.

简单的例子:

var attributeActions = new Dictionary<string, Action>();
attributeActions["level1A"] = () => { /* do something */ };
attributeActions["level2A"] = () => { /* do something else */ };

...
// call it
attributActions[node.Attributes["name"]]();

您需要检查的关键确实存在,但你可以做的扩展方法是封装的功能:

You would need to check that the key actually exists but you could make extension method for that to encapsulate that functionality:

public static void Execute<TKey>(this IDictionary<TKey, Action> actionMap, TKey key)
{
    Action action;
    if (actionMap.TryGet(key, out action))
    {
         action();
    }
}

然后,你可以这样调用它:

Then you can call it like this:

attributActions.Execute(node.Attributes["name"]);

而不是一个动作(这是一个无参数片段返回无效),你可能想使用动作&LT; T&GT; Func键&LT; T,R&GT; 的情况下,你需要传递paramters和/或获取返回值

Instead of an Action (which is a parameterless snippet returning void) you might want to use Action<T> or Func<T, R> in case you need to pass paramters and/or get return values.