To help you get to the last child node of a node, XPath proposes a function named last. Therefore, to get the last child node, pass last() as the index of the node that acts as the parent. 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;
// This expression first gets the 2nd video.
// Then it gets the 3rd actor of that video
XmlNodeList xnlVideos = xeVideo.SelectNodes("/videos/video[last()]");
foreach(XmlNode xnVideo in xnlVideos)
MessageBox.Show(string.Format("Video: {0}",
xnVideo.OuterXml),
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
This would produce:
As an alternative, you can assign last() to position(). 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("/videos/video[position() = last()]");
foreach(XmlNode xnVideo in xnlVideos)
MessageBox.Show(string.Format("Video: {0}",
xnVideo.OuterXml),
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
Consider the following 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("/videos/video/cast-members[last()]");
foreach(XmlNode xnVideo in xnlVideos)
MessageBox.Show(string.Format("Last cast-members section of any video " +
"that has a cast-members section\n" +
"____________________________________________________\n{0}",
xnVideo.OuterXml),
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
This would produce:
Notice that the result includes all nodes from a parent that has a cast-members section. If you want to get only the last node that has that section, include the whole path in parentheses excluding the square brackets and their index. 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("(/videos/video/cast-members)[last()]");
foreach(XmlNode xnVideo in xnlVideos)
MessageBox.Show(string.Format("Last cast-members section\n" +
"____________________________________________________\n{0}",
xnVideo.InnerXml),
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return 0;
}
}
This would produce:
|
|
|||
|
|