【问题标题】:Navigate between XML Elements with Same Attribute在具有相同属性的 XML 元素之间导航
【发布时间】:2018-08-22 01:13:41
【问题描述】:

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

假设这是一个 xml 文档:

parent1
    child1 attributeA
    child2 attributeA

parent2
    child3 attributeA
    child4 attributeB

我想在任何带有属性 A 的东西之间导航下一个和上一个按钮,所以如果我在 parent1/child2,下一个将是 parent2/child3,而上一个将是 parent1/child1。

可以新建一个XML Document,可以加载,可以获取当前节点,但是不知道next和previous。

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

谁能帮忙?

【问题讨论】:

  • 不要使用 xpath 和 xmldocument。使用较新的 Net Library xml linq 非常简单。
  • 使用 xml linq,您可以获得具有该属性的元素列表。像这样的东西:doc.Descendants().Where(x => x.Attribute("attributeA") != null).ToList()。获得列表后,导航到上一个和下一个应该很简单。

标签: c# xml xpath xmldocument


【解决方案1】:

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] 的路径归结为:

//"一层或多层深"

*“任意元素”

[@attributeA]“带有属性‘attributeA’”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多