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

C# 在具有相同属性的XML元素之间导航,c#,xml,xpath,xmldocument,C#,Xml,Xpath,Xmldocument,我正在做一个C#/ASP.Net项目 假设这是一个xml文档: parent1 child1 attributeA child2 attributeA parent2 child3 attributeA child4 attributeB 我想使用“下一步”和“上一步”按钮在带有attributeA的任何内容之间导航,因此,如果我位于parent1/child2,则下一步将是parent2/child3,上一步将是parent1/child1 我可以创建一个新

我正在做一个C#/ASP.Net项目

假设这是一个xml文档:

parent1
    child1 attributeA
    child2 attributeA

parent2
    child3 attributeA
    child4 attributeB
我想使用“下一步”和“上一步”按钮在带有attributeA的任何内容之间导航,因此,如果我位于parent1/child2,则下一步将是parent2/child3,上一步将是parent1/child1

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

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

有人能帮忙吗?

但是此代码应该为您提供所有具有
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'”

请勿使用xpath和xmldocument。使用较新的网络库XMLLINQ非常简单。使用XMLLINQ,您可以获得具有该属性的元素列表。类似这样的内容:doc.subjects().Where(x=>x.Attribute(“attributeA”)!=null.ToList()。一旦你有了列表,就可以很容易地导航到上一个和下一个。