在具有相同属性的 XML 个元素之间导航

Navigate between XML Elements with Same Attribute

我正在开发 C#/ASP.Net 项目。

假设这是一个 xml 文档:

parent1
    child1 attributeA
    child2 attributeA

parent2
    child3 attributeA
    child4 attributeB

我想在具有 attributeA 的任何内容之间使用下一个和上一个按钮导航,因此如果我在 parent1/child2,下一个将是 parent2/child3,上一个将是 parent1/child1。

我可以创建一个新的XML文档,我可以加载它,我可以获取当前节点,但我不知道下一个和上一个。

我该怎么做?好久没做 xpaths 了。很长一段时间。我在这里四处寻找类似的东西,但要么不存在,要么找不到。

有人可以帮忙吗?

The MSDN has a nice article about XPaths with great examples

但是这段代码应该给你所有有 attributeA 的节点,不管它们嵌套在 XML 中的什么地方:

var doc = new XmlDocument();
doc.Load(@"C:\path\to\file.xml");
XmlNodeList nodes = doc.SelectNodes("//*[@attributeA]");
foreach (var node in nodes)
{
    // your code here
}

路径 //*[@attributeA] 归结为:

// "one or more levels deep"

* "any element"

[@attributeA] "with attribute 'attributeA'"