使用 XPath:
ClickedNode.XPathEvaluate
("self::Employee | self::Manager/Employee[1] | self::root/Manager[1]/Employee[1]")
更新:
回答已编辑的问题:
使用:
ClickedNode[self::Employee]
|
ClickedNode[not(self::Employee)]/descendant-or-self::Manager[Employee][1]/Employee[1]
这选择:
一个。单击的节点,如果它是“员工”
或者:
湾。单击节点的第一个子Employee
节点的第一个子节点,即管理器并有一个子节点Employee
并且,如果 ClickedNode 是XElement
(或XNode
),则执行以下操作:
ClickedNode.XPathEvaluate
(self::*[self::Employee]
| self::node()[not(self::Employee)]
/descendant-or-self::Manager[Employee][1]/Employee[1]
)
最后,这是一个完整的 C# 代码:
一个名为的静态类TestLinqXpath
:
using System.Xml.Linq;
using System.Xml.XPath;
namespace TestLinqXpath
{
public static class TestLinqXpath
{
public static XElement SelectNearestDescendantEmployee(XElement clicked)
{
string Expr =
@"(self::*[self::Employee]
| self::node()[not(self::Employee)]
/descendant-or-self::Manager[Employee][1]/Employee[1]
)";
XElement result = clicked.XPathSelectElement(Expr);
return result;
}
}
}
和广泛的测试:
using System;
using System.Xml.Linq;
using System.Xml.XPath;
namespace TestLINQ_Xml
{
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
string xml =
@"<root>
<Manager name='1'>
<Manager name='2'>
<Employee name='3'/>
</Manager>
<Manager name='abe'>
</Manager>
<Employee name='4'/>
<Employee name='5'/>
</Manager>
</root>";
XElement top = XElement.Parse(xml);
XElement cliked1 = top;
XElement res1 = TestLinqXpath.TestLinqXpath.SelectNearestDescendantEmployee(cliked1);
Console.WriteLine(res1.ToString());
XElement cliked2 = top.XPathSelectElement("Manager[@name='1']");
XElement res2 = TestLinqXpath.TestLinqXpath.SelectNearestDescendantEmployee(cliked2);
Console.WriteLine(res2.ToString());
XElement cliked3 = top.XPathSelectElement(".//Manager[@name='2']");
XElement res3 = TestLinqXpath.TestLinqXpath.SelectNearestDescendantEmployee(cliked3);
Console.WriteLine(res3.ToString());
XElement cliked4 = top.XPathSelectElement(".//Manager[@name='abe']");
XElement res4 = TestLinqXpath.TestLinqXpath.SelectNearestDescendantEmployee(cliked4);
Console.WriteLine((res4 != null) ? res4.ToString() : "null");
XElement cliked5 = top.XPathSelectElement(".//Employee[@name='5']");
XElement res5 = TestLinqXpath.TestLinqXpath.SelectNearestDescendantEmployee(cliked5);
Console.WriteLine(res5.ToString());
}
}
}
运行此测试时,会产生所需的正确结果:
<Employee name="4" />
<Employee name="4" />
<Employee name="3" />
null
<Employee name="5" />