递归地使用XPath递归选择子节点?

时间:2011-11-22 06:50:50

标签: c# xpath

给出以下XML:

<Checks>
   <IsSomethingCheck Param="1"/>
   <IsSomeoneCheck Param2="2"/>
   <Checks Operator="Or">
       <IsAnythingCheck Param3="3"/>
   </Checks>
</Checks>

如何递归遍历Checks元素的子元素?

下面的代码适用于最外面的子代,但是停止处理最内层的子代(内部Checks元素的一部分)

protected override void InitializePlugin(XmlElement xmlElement)
{
    Enum.TryParse(xmlElement.GetAttribute("Operator"), out _operator);

    XPathNodeIterator nav = xmlElement.CreateNavigator().Select("Checks/*");

    foreach (XPathNavigator checkNode in nav)
    {
        if (_checksLookup.ContainsKey(checkNode.Name))
        {
            Type checkType = _checksLookup[checkNode.Name];
            Check check = Activator.CreateInstance(checkType) as Check;
            check.Initialize(checkNode.OuterXml);
            Checks.Add(check);
        }
    }    
}

PS:此方法的XmlElement期望它将接收XML的整个Checks部分。

1 个答案:

答案 0 :(得分:2)

发现它! XPath表达式应该是/CheckManager/*而不是CheckManager/*