读取XML并根据属性执行操作

假设我有一个XML文件,例如:

                                

如何根据元素读取此文件并执行代码片段? 例如,如果“name”元素显示“level7a”,则执行代码片段X.如果name元素表示level7B,则执行代码片段Y.

如果能让答案更容易,我可以提供这样的代码片段。 谢谢您的帮助!

您可以创建一个Dictionary ,它将属性名称映射到actions。 然后在解析xml时,您可以在字典中查找片段并执行它。

快速举例:

 var attributeActions = new Dictionary(); attributeActions["level1A"] = () => { /* do something */ }; attributeActions["level2A"] = () => { /* do something else */ }; ... // call it attributActions[node.Attributes["name"]](); 

您需要检查密钥是否确实存在,但您可以使用扩展方法来封装该function:

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

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

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

而不是Action (无参数片段返回void ),您可能希望使用ActionFunc ,以防您需要传递参数和/或获取返回值。

看来你需要两件事:

  1. 按照特定的顺序浏览文件(元素),我猜深度优先

  2. 基于字符串值执行操作。

这应该给你一个粗略的想法:

  var doc = System.Xml.Linq.XDocument.Load(fileName); Visit(doc.Root); private static void Visit(XElement element) { string name = element.Attribute("name").Value; Execute(name); // you seem to have just 1 child, this will handle multiple // adjust to select only elements with a specific name foreach (var child in element.Elements()) Visit(child); } private static void Execute(string name) { switch (name) { case "level1A" : // snippet a break; // more cases } } 

这个想法归功于@ChrisWue。 这是一个不同的看法,它调用显式定义的方法而不是匿名的方法:

 private Dictionary actionList = new Dictionary(); private void method1() { } private void method2() { } private void buildActionList() { actionList.Add("level7a", new Action(method1)); actionList.Add("level7B", new Action(method2)); // .. etc } public void processDoc() { buildActionList(); foreach (XElement e in (XDocument.Parse(File.ReadAllText(@"C:\somefile.xml")).Elements())) { string name = e.Attribute("name").Value; if (name != null && actionList.ContainsKey(name)) { actionList[name].Invoke(); } } } 

..显然,实际上会在method1,method2等的主体中放置一些东西。