The ancestors of a node are its parent and grand-parent, up to the root of the XML file. To get the ancestors of a node, precede its name with the ancestor keyword. Here is an example: using System;
using System.Xml;
using System.Windows.Forms;
public class Exercise
{
public static int Main()
{
XmlDocument xdVideos = new XmlDocument();
xdVideos.Load("../../Videos.xml");
XmlElement xeVideo = xdVideos.DocumentElement;
XmlNodeList xnlVideos = xeVideo.SelectNodes("//ancestor::video");
foreach (XmlNode xnVideo in xnlVideos)
MessageBox.Show(xnVideo.InnerXml,
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
The descendants of a node are its child(ren) and grand-child(ren), down to the last grand-child of that node. To get the descendants of a node, precede its name with the descendant keyword.
The previous sibling of a node is a node that comes before it in the tree while both nodes are on the same level. To get the collection of nodes that come before a certain node, precede its name with the preceding keyword. Here is an example: using System;
using System.Xml;
using System.Windows.Forms;
public class Exercise
{
public static int Main()
{
XmlDocument xdVideos = new XmlDocument();
xdVideos.Load("Videos.xml");
XmlElement xeVideo = xdVideos.DocumentElement;
XmlNodeList xnlVideos = xeVideo.SelectNodes("//preceding::categories");
foreach (XmlNode xnVideo in xnlVideos)
MessageBox.Show(xnVideo.OuterXml,
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
If your expression indludes the preceding keyword, the result would include the node itself and the next node of the same name in the same tree level. If you want to exclude the node itself from the result, in other words if you want to get only the next sibliing of the same level, use the preceding-sibling keyword.
The following keyword is used to get the next node(s) that come after the referenced one but of the same tree level. Consider the following expression: using System;
using System.Xml;
using System.Windows.Forms;
public class Exercise : Form
{
public static int Main()
{
XmlDocument xdVideos = new XmlDocument();
xdVideos.Load("../../Videos.xml");
XmlElement xeVideo = xdVideos.DocumentElement;
XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video/following::director");
foreach (XmlNode xnVideo in xnlVideos)
MessageBox.Show(xnVideo.OuterXml,
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
This code would access the director nodes, excluding the first one. |
|
|||||||||
|
|