开发者

Encapsulating Nested XML

I'm trying to find an elegant way of encapsulating XML into a C# class. Looking around, I found a Java example somewhere (don't ask me where at this point) that sparked an idea, but I'm not sure if it's even possible in C# or if I'm going about it the right way.

The inelegant method I'm using currently is to iterate through XPathNodeIterator/XPathNavigator nodes with a whole series of nested switch statements that indicate what to do once the appropriate node is found, and also list any nodes that were unhandled. The more elegant method I'm trying involves using a helper class to do the bulk of the iteration and basically takes a node name and what Action to take when that node is encountered. That class looks like this currently (note that this is theoretical, see below for why):

class XmlNodeIterator
{
    public XmlNodeIterator(XPathNodeIterator node, Dictionary<string, Action> children)
    {
        foreach (XPathNavigator childNode in node.Current.SelectChildren(XPathNodeType.Element))
        {
            Action child = null;
            try
            {
                child = children[childNode.LocalName];
            }
            catch (KeyNotFoundException e)
            {
                // Log the warning in some 开发者_JAVA技巧fashion
            }
            if (child != null)
                child.Invoke();
        }
    }
}

Before I even got to proof-of-concept testing, I discovered a problem with the concept. :) How can I access the inner childNode (e.g., childNode.Value or childNode.GetAttribute) in the delegate function and assign it to an outer variable or property?

I'm still really new to delegates in general, so I have no idea if this is even possible. If it is, great! If not, are there any other elegant solutions I can try? Or should I just stick with nested switches?


Consider using Action<T> instead of Action. It's Invoke method can be called with parameter. In your case:

Action<XPathNavigator> child = null;
...
child.Invoke(childNode);

Or if you want to assign any outer values you can use Func<T1,T2> like that:

Func<XPathNavigator, string> child = null;
...
var value = child(childNode);

Btw, as shown in 2nd example, direct Invoke call can be omited. We can simply call it as a method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜