An understanding on the usage of Single Slash /
and Double slash //
can help here.
Let's see how /
and //
work in relation to the root node. When /
is used at the beginning of a path:
/a
it will define an absolute path to node a
relative to the root. As such, in this case, it will only find a
nodes at the root of the XML tree.
When //
is used at the beginning of a path:
//a
it will define a path to node a
anywhere within the XML document. As such, in this case, it will find a
nodes located at any depth within the XML tree.
These XPath expressions can also be used in the middle of an XPath value to define ancestor-descendant relationships. When /
is used in the middle of a path:
/a/b
it will define a path to node b
that is an immediate direct descendant (ie. a child) of node a
.
When //
used in the middle of a path:
/a//b
it will define a path to node b
that is ANY descendant of node a
.
Coming back to your question:
// using GetElementsByTagName()
return all the Elements having name: Red_Fruits
XmlDocument doc = new XmlDocument();
XmlNodeList nodes= doc.GetElementsByTagName("Red_Fruits");
//Using SelectNodes()
method
XmlNodelist nodes = doc.SelectNodes("//Fruits/Red_Fruits");
// This will select all elements that are children of the <Fruits>
element.
In case <Fruits>
is the root element use the Xpath: /Fruits/Red_Fruits
. [ a single slash /
]