Home

Introduction

 

Fundamentals

 

Introduction

 

 

     
 
 

 

   
   
 

Previous Copyright © 2015 FunctionX Next

Home

F# and XML: XPath

 

XPath Fundamentals

 

Introduction to XPath

If you have used UNIX, Microsoft Windows, Linux, or any operating system, you are probably familiar with the most common operation which consists of locating a file. In fact, the primary characteristic of a file is its location, which is analogous to the address of a house. By that analogy, to locate a house in the city or anywhere, you must follow a path. When it comes to an operating system, every location starts from a drive such as a hard drive, an optical drive (CD, DVD, BD), a USB drive, etc. Inside that drive are directories or folders. Such directories or folders can contain child directories or child folders, also called sub-directories or sub-folders. Those also can have children or sub-directories/sub-folders. At the end, there are files. In reality, a file can belong to any directory, including the root.

You are probably familiar with how hard it can be to locate an element in an XML file. Fortunately, the MSXML library provides various mechanisms through some classes and their methods. Such techniques are available only if you are using MSXML or the .NET Framework. To provide a common mechanism to locate the elements in an XML document, the W3C created the XPath language.

Introduction to XPath and .NET

Microsoft supports XPath in various ways, as a language in its own right, in the MSXML library, and in the .NET Framework. In this lesson, we will use or address XPath as it is defined by W3C and as it is, or can be, used in the .NET Framework or in a .NET Framework-based application.

To support XPath, the .NET Framework provides the System.Xml.XPath namespace that contains various classes. As you should know already, the .NET Framework primarily supports the XML standards through the System.Xml namespace that contains such valuable classes as XmlDocument, XmlElement, XmlNode, and XmlNodeList (and many other important classes). The XmlDocument class gives access to the whole contents of an XML document, starting with the root node, which is represented by the DocumentElement property.

As you may know already, to open an XML file you can pass its path to the Load() method of the XmlDocument class. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document",
			     Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load strFileName
        fsVideo.Close()

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

If the path is invalid or the file cannot be found, the compiler would throw a FileNotFoundException exception:

If the path is invalid or the file cannot be found, the compiler would throw a FileNotFoundException exception

Otherwise, that is, if the file could be found, you can use the document as you see fit. For example, you can access its root through the DocumentElement property:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load strFileName
        fsVideo.Close()

        let xeVideo : XmlElement = xdVideos.DocumentElement
        
        . . .
        
btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

From that root, you can "scan" (or navigate) the XML document for any reason. The XmlDocument.DocumentElement property is of type XmlElement, which is derived from XmlLinkedNode, itself a child of the XmlNode class.

An XPath Expression

 

Introduction

As you have used operating systems before, you are familiar with the way the address of a file is formulated. In Microsoft Windows, an example of the location of a folder is:

H:\Programming\Lessons\

This gives access to the Lessons sub-folder that is a child of the Programming folder created in the H drive. An example of the location of a file is:

H:\Programming\Lessons\Lesson01.htm

This gives access to the Lesson01.htm file located in the Lessons sub-folder that is a child of the Programming folder created in the H drive. You can pass such a location to a method of a class, for example if you are performing file processing using one of the classes of the System.IO namespace. A file location is considered an expression. Such an expression contains words (for example Lessons) and operators (such as . or : or \). In the same way, the XPath language uses expressions to specify a path. XPath uses expressions. Internally, there is a program called the XPath parser, or just the parser. That parser receives the expression and analyzes it. When the parser has finished doing its job, it sends its report to the F# compiler.

To give you the ability to use XPath, the XmlNode class is equipped with a method named SelectNodes. This method is overloaded with two versions. The signature of one of the versions is:

member SelectNodes : 
        xpath:string -> XmlNodeList

As you can see, the XmlNode.SelectNodes() method takes an XPath expression passed as a string. This can be illustrated as follows:

XPath

If the XmlNode.SelectNodes() method succeeds in what it is supposed to do, it returns a name, a value, a string, or a list of nodes, as an XmlNodeList collection. This can be done as follows:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "XPath Expression"

	. . .
	
btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Remember that the XmlNodeList class starts as follows:

type XmlNodeList =  
    class 
        interface IEnumerable 
        interface IDisposable 
    end

Since XPath is a language, it has rules that an expression must follow. An expression that follows the rules is referred to as well-formed. In our use of XPath, two rules will apply: first, the rules of the XPath language, followed by the rules of the F# language. The primary rule of XPath is that the expression you formulate must be valid (be well-formed). If the expression doesn't follow the rules or the expression violates a rule (that is, if the expression is not well-formed, if you didn't follow the XPath rules), its parser concludes that the expression is not valid. The parser stops any processing and sends a report to the F# compiler. The F# compiler would not perform any further processing and it would throw an exception named XPathException. Here is an example of the compiler displaying an error:

If the path is invalid or the file cannot be found, the compiler would throw a FileNotFoundException exception

The XPathException is defined in the System.Xml.XPath namespace. If you want, you can catch that exception and take appropriate measures (of course, this class has a Message property).

If the XPath expression is valid, the parser hands the job to another program referred to as an interpreter. Its job is to produce the result requested by the XPath expression. The interpreter starts "scanning" the document that was initiated by the XmlDocument.DocumentElement object. We will see various types of operations that can be requested. For example, you may ask the interpreter to look for a certain element. Another operation may consist of comparing two values. The interpreter checks the document from beginning to end. If it doesn't find any element that responds to the expression, the interpreter sends a message to the F# compiler that no result was found. In this case, the XmlNode.SelectNodes() method returns null.

Starting from the beginning of the document, if the interpreter finds a node that responds to the XPath expression, it adds it to its list of results and continues checking the nodes in the document. When it reaches the end of the document, it gets its final list and sends it to the F# compiler. The compiler stores that list in an XmlNodeList collection and makes it the returned list of the XmlNode.SelectNodes() method. You can then use that list as you see fit. Since the XmlNodeList class holds a collection, you can use a for ... in loop to "scan" it. Consider the following XML document whose file is named Videos.xml:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video>
    <title>The War of the Roses</title>
    <director>Danny DeVito</director>
    <cast-members>
      <actor>Michael Douglas</actor>
      <actor>Kathleen Turner</actor>
      <actor>Danny DeVito</actor>
    </cast-members>
  </video>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <cast-members>
      <actor>Eddie Murphy</actor>
      <actor>Lane Smith</actor>
      <actor>Sheryl Lee Ralph</actor>
      <actor>Joe Don Baker</actor>
      <actor>Victoria Rowell</actor>
    </cast-members>
    <cast-members>
      <actor>Charles S. Dutton</actor>
      <actor>Grant Shaud</actor>
      <actor>Kevin McCarthy</actor>
      <actor>Victor Rivers</actor>
      <actor>Chi McBride</actor>
      <actor>Noble Willingham</actor>
    </cast-members>
    <length>112</length>
    <format>DVD</format>
    <rating>R</rating>
    <year-released>1992</year-released>
    <categories>
      <genre>Comedy</genre>
      <genre>Politics</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>government</keyword>
        <keyword>con artist</keyword>
        <keyword>lobbyist</keyword>
        <keyword>election</keyword>
      </keywords>
    </categories>
  </video>
  <video>
    <title>Duplex</title>
    <director>Danny DeVito</director>
    <cast-members>
      <narrator>Danny DeVito</narrator>
    </cast-members>
  </video>
  <video>
    <title>The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124</length>
    <categories>
      <genre>Drama</genre>
      <genre>Environment</genre>
      <genre>Science Fiction</genre>
    </categories>
    <format>BD</format>
    <rating>PG-13</rating>
    <keywords>
      <keyword>climate</keyword>
      <keyword>global warming</keyword>
      <keyword>disaster</keyword>
      <keyword>new york</keyword>
    </keywords>
  </video>
  <video>
    <title>Other People&#039;s Money</title>
    <director>Alan Brunstein</director>
    <year-released>1991</year-released>
    <cast-members>
      <actor>Danny DeVito</actor>
      <actor>Gregory Peck</actor>
      <actor>Penelope Ann Miller</actor>
    </cast-members>
    <cast-members>
      <actor>Dean Jones</actor>
      <actor>Piper Laurie</actor>
    </cast-members>
    <categories>
      <genre>Comedy</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>female stocking</keyword>
        <keyword>seduction</keyword>
      </keywords>
      <genre>Business</genre>
      <keywords>
        <keyword>capitalism</keyword>
        <keyword>corporate take-over</keyword>
        <keyword>factory</keyword>
        <keyword>speech</keyword>
        <keyword>public speaking</keyword>
      </keywords>
      <genre>Drama</genre>
      <keywords>
        <keyword>play</keyword>
        <keyword>hostile take-over</keyword>
        <keyword>corporate raider</keyword>
      </keywords>
    </categories>
  </video>
</videos>

The Root

As you may know already, every XML document starts with a root node. If you don't know the name of the root (this could happen if you are using an XML file created by someone else and you are not familiar with the document's structure), you can pass the argument to XmlElement.SelectNodes(string xpath) method as /. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/"

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Both the XPath language and the .NET Framework provide various means to present the result of an XPath expression. As we will see in the next sections, the XPath language provides various operators such as the forward slash / to specify the path, or where to start considering the path, to a node. On the other hand, the XmlNode class is equipped with the InnerText, the InnerXml, and the OuterXml properties that produce various results as we will see.

As you should know already, the XmlNode.InnerText property produces the value of an element. The XmlNode.InnerXml property produces the tag (start and end) and the name of an element. The XmlNode.OuterXml property produces a node and its XML format, including the child nodes, if any, of the element. Here is an example that uses the XmlNode.OuterXml property:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

XPath Root

An alternative to access the root node is to pass /* as a string to XmlElement.SelectNodes(). Here is an example:

let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/*"

One more alternative is to pass the name of the root preceded by /. Here is an example:

let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos"

This would produce the same result as above. Notice that the whole document is treated as one object (the result includes only one Result).

Accessing the Child Nodes of the Root

In an XML document, the root can have 0 or more child nodes. To access the nodes that are direct children of the root, pass the expression as /RootName/ChildOfRootName. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video"

    for xnVideo in xnlVideos do
        MessageBox.Show("Video\n" + xnVideo.OuterXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing the Child Nodes of the Root

Accessing the Child Nodes of the Root

Accessing the Child Nodes of the Root

Accessing the Child Nodes of the Root

Accessing the Child Nodes of the Root

Notice that this time, each child node of the root is considered an item of the resulting collection.

Accessing Other Children

To access a child node whose location is clear, start from the root and list the ancestry, separating the items by /. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(170, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxDirectors  = new ListBox(Location = new Point(12, 12),
				Size = new System.Drawing.Size(145, 90))
exercise.Controls.Add lbxDirectors

let strFileName = "..\..\Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/director"

    for xnVideo in xnlVideos do
        lbxDirectors.Items.Add xnVideo.InnerText |> ignore

    fsVideo.Close()
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Other Children

You can use this technique to locate a node. You can check the results to find a particular node you are looking for.

Accessing the Child Nodes of an Element

A child is a node that appears immediately down after a node in the ancestry lineage. To access the child nodes of an element, follow its name with /*. With this operator, if the immediate child node of the element is:

Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(1080, 220),
                        StartPosition = FormStartPosition.CenterScreen)

let rtbVideos = new RichTextBox(Location = new Point(12, 12),
                                Size = new System.Drawing.Size(1060, 190))
exercise.Controls.Add rtbVideos

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//video"

    let videos = [| for i in 0 .. xnlVideos.Count - 1 -> "" |]

    for i in 0 .. xnlVideos.Count - 1 do
        videos.[i] <- xnlVideos.[i].OuterXml

    rtbVideos.Lines <- videos

    fsVideo.Close()
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Other Children

As stated already, if the last element of the expression you passed includes a child node that itself has child nodes, all those child nodes would be combined and produced as one object. If you want to get the individual nodes, pass their name after that of the element. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(325, 185),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxCategories = new ListBox(Location = new Point(12, 12),
                                Size = new System.Drawing.Size(300, 170))
exercise.Controls.Add lbxCategories

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//video/categories/*"

    let videos = [| for i in 0 .. xnlVideos.Count - 1 -> "" |]

    for xnVideo in xnlVideos do
        lbxCategories.Items.Add xnVideo.InnerText |> ignore

    fsVideo.Close()
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing the Child Nodes of an Element

Accessing the Grand-Children of a Node

A grand-child is a node that appears down after the child node in the ancestry lineage. To access the grandchildren of a node, separate its name and that of the grand-child name with /*/. Here is an example:

let xnlVideos = xeVideo.SelectNodes "/videos/*/director"

This example is based on the root and it produces the same result as seen above. Otherwise, if you are starting from another level, make sure you specify it. Here is an example:

let xnlVideos = xeVideo.SelectNodes "/videos/video/*/actor"

Accessing Specific Nodes

If you have many elements that share the same name in your XML document, to access those elements, pass their name preceded by //. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(325, 185),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxDirectors = new ListBox(Location = new Point(12, 12),
                                Size = new System.Drawing.Size(300, 170))
exercise.Controls.Add lbxDirectors

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//director"

    let videos = [| for i in 0 .. xnlVideos.Count - 1 -> "" |]

    for xnVideo in xnlVideos do
        lbxDirectors.Items.Add xnVideo.InnerText |> ignore

    fsVideo.Close()
[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce the same result as above. You can also precede // with a period as follows:

let xnlVideos : XmlNodeList = xeVideo.SelectNodes ".//director"

Consider the following example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "..\..\Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//cast-members"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Specific Nodes

Accessing Specific Nodes

Accessing Specific Nodes

Accessing Specific Nodes

Notice that the results in each section, those belonging to the same parent node, are treated as one object. If you pass the common name of the nodes that are at the end of their ancestry, they would be treated individually. Consider the following example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxActors = new ListBox(Location = new Point(12, 12), Width = 100)
exercise.Controls.Add lbxActors

let strFileName = "..\..\Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//actor"

    for xnVideo in xnlVideos do
        lbxActors.Items.Add(xnVideo.InnerText |> ignore

    fsVideo.Close()

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Specific Nodes

In the same way, you can use the // operator to specify where to start considering a path to a child or grand-child node. Here is an example:

let xnlVideos = xeVideo.SelectNodes "//video/*/actor"

In the same way, you can combine operators (separators) to get to a node. For example, to get the child of a node X that itself is a grandchild, simple follow that X node with / and the name of the child. Here is an example:

let xnlVideos = xeVideo.SelectNodes "//videos/*/cast-members/actor"

XPath and Arrays

 

Introduction

If you pass an expression that accesses many nodes on the same level and the expression produces many results, as you know already, the results are stored in an XmlNodeList collection. Based on the XPath standards, those results are stored in an array.

Accessing a Node by its Position

When accessing the results of an XPath expression, each result uses a specific position in the resulting array. The position corresponds to the index of arrays seen in F#, except that the indexes start at 1. The first result is positioned at index 1, the second at index 2, until the end.

To access an individual result of the XPath expression, use the square brackets as done in C-based languages. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnDocument = new Button(Text = "Document", Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnDocument

let btnDocumentClick _ =
    let strFileName = "../../Videos.xml"
    let xdVideos : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdVideos.Load fsVideo
        fsVideo.Close()

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[1]"

    for xnVideo in xnlVideos do
        MessageBox.Show(String.Format("First Video\n{0}", xnVideo.OuterXml),
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

btnDocument.Click.Add btnDocumentClick

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing a Node by its Position

The array technique can be very valuable if the results are made of single values, such as the names of people. Consider the following example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(275, 280),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxAllActors = new ListBox(Location = new Point(12, 12), Size = new System.Drawing.Size(120, 260))
exercise.Controls.Add lbxAllActors

let lbxLeadingActors = new ListBox(Location = new Point(145, 12), Size = new System.Drawing.Size(120, 260))
exercise.Controls.Add lbxLeadingActors

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let mutable xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/cast-members/actor"

    for xnVideo in xnlVideos do
        lbxAllActors.Items.Add xnVideo.InnerText |> ignore

    xnlVideos <- xeVideo.SelectNodes "//videos/video/cast-members/actor[1]"

    for xnVideo in xnlVideos do
        lbxLeadingActors.Items.Add xnVideo.InnerText |> ignore
    
    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce the first actor in each section (each child of the root):

Accessing a Node by its Position

If you pass an index that is not found, such as one that is higher than the number of results, the method would return nothing (no exception would be thrown).

Once you have accessed a node by its position, if that node has at least one child node, you can access that child node using / and its name. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(275, 280),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let mutable xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[2]/cast-members"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Videos with both Format and Category sections",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
    
    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing a Node by its Position

Accessing the Lineage by Position

If the element on which you apply the square brackets has child nodes, you can apply the square brackets on the child nodes to get one at a position of your choice. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(275, 280),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let mutable xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos[1]/video[3]"

    for xnVideo in xnlVideos do
        MessageBox.Show("Video\n" + xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
    
    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0   

This would produce:

Accessing the Lineage by Position

In the same way, you can apply the square brackets to any child node of an element. Here is an example:

let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos[1]/video[4]/categories[1]/genre[3]")

The rules to remember are:

Using these features of arrays applied to XPath, you can access any node. For example, you can apply the square brackets to a certain node and access it by its position. If the node at that position has child nodes, you can use the name of those child nodes and apply the square brackets on that name to indicate what node you want to access. Consider the following example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let txtActor = new TextBox(Location = new Point(60, 12))
exercise.Controls.Add txtActor

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[2]/cast-members/actor[3]"

    for xnVideo in xnlVideos do
        txtActor.Text <- xnVideo.InnerText
    
    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing a Node by its Position

The First Child Node of the Root

As mentioned already, all the child nodes of an element are stored in an array. In fact, if you pass the name of the root as your XPath expression, this is equivalent to applying [1] to it. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

exercise.Controls.Add(new Label(AutoSize = true, Text = "Actor:", Location = new Point(12, 14)))

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos[1]"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Accessing a Node by its Name

By using arrays, the XPath language makes it possible to get a collection of nodes based on their common name. To get only the nodes that have a specific section, pass the name of that section to the square brackets of the parent element. From our XML document, imagine you want only the videos that have a section named cast-members. Here is an example of getting them:

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;
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos/video[cast-members]");    

	for xnVideo in xnlVideos do
	    MessageBox.Show(string.Format("Video --------------------------------------------------------------------\n{0}",
                            xnVideo.OuterXml),
			    "Videos that have a cast-members section",
			    MessageBoxButtons.OK,
			    MessageBoxIcon.Information) |> ignore

	return 0;
    }
}

This would produce:

Accessing a Node by its Name

Accessing a Node by its Name

Accessing a Node by its Name

Accessing a Node by its Name

Notice that, in our XML document, only some of the videos include the list of actors. If you pass a name that doesn't exist, the interpreter would produce an empty result (no exception would be thrown).

Locating a Specific Node by its Name

Considering the following XPath expression:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/cast-members[actor]"
    
    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Videos with both Format and Category sections",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0   

This would produce all cast-members sections of all videos (only the cast-members section). If you want to get a only a specific child node, assign its value to the name in the square brackets. 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;
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos/video/cast-members[actor = 'Penelope Ann Miller']");    

	for xnVideo in xnlVideos do
	    MessageBox.Show(xnVideo.OuterXml,
			    "Videos with both Format and Category sections",
			    MessageBoxButtons.OK,
			    MessageBoxIcon.Information) |> ignore

	return 0;
    }
}

Based on our XML document, the result would produce only the cast-members sections that include Penelope Ann Miller. Here is an example:

Locating a Specific Node by its Name

Accessing the Grand-Children of a Node by its Name

After accessing a node by name, if it has at least one child node, you can access it/them by passing its/their name after the parent and /. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[categories]/keywords"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Grand-Children of a Node by its Name

Accessing a Node by its Value

If you want to locate a specific child node, in the square brackets, type .= and the value of the node. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes"/videos/video/cast-members/actor[. = 'Eddie Murphy']"   

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerText,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

Accessing the Nodes With Specific Grand-Children

To get only the parent nodes that have child nodes that in turn have certain child nodes, in the square brackets, type the names of the child node and grand-child separated by /. Here an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[categories/keywords]"
    
    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

From our XML file, this would produce only the videos that have a categories section but that categories section must have a keywords section as child, which excludes a video where the categories and their keywords are children on the same level:

Accessing the Nodes With Specific Grand-Children

Accessing the Nodes With Specific Grand-Children

Accessing the Grand-Children by Position

Notice that our XML document has some videos that have a cast-members section. Instead of getting all of them, you can ask the interpreter to return only the one at a specific position. This is done by adding a second pair of square brackets and passing the desired index. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[cast-members][2]"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0    

This would produce:

Accessing the Grand-Children by Position

Accessing the Grand-Children by Name

After getting a child node by name, if that child node has at least one child node and you know the name of that grand-child, pass that name to the square brackets applied after /. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes"/videos/video[categories]/keywords[keyword]"
    
    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0	

This would produce:

Accessing the Grand-Children by Position

XPath Functions

 

Introduction

The XPath language provides many functions. Some functions are made to perform some of the operations we have applied already. Some other functions are meant to produce some results we have not gotten so far.

The Position of a Node

We have seen that we can use the square brackets to get to the position of a node. The XPath language has a function named position that can be used to access a node based on its position. To use it, in the square brackets of the node that is considered the parent, assign the desired position to position().

As you may know already, the first child of a node has an index of 1. Therefore, to get the first child node, assign 1 to the position() function. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos/video[position() = 1]");    

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

The Position of a Node

In the same way, to get to any node, assign its index to position().

The Last Child Node

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:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    // This expression first gets the 2nd video.
    // Then it gets the 3rd actor of that video
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[last()]"

    for xnVideo in xnlVideos do
        MessageBox.Show(String.Format("Video: {0}", xnVideo.OuterXml),
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

The Last Child Node

As an alternative, you can assign last() to position(). Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[position() = last()]"

    for xnVideo in xnlVideos do
        MessageBox.Show(String.Format("Video: {0}", xnVideo.OuterXml),
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0   

Consider the following example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/cast-members[last()]"    

    for xnVideo in xnlVideos do
        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) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes();    

This would produce:

The Last Child Node

The Last Child Node

The Last Child Node

The Last Child Node

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:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "(/videos/video/cast-members)[last()]"

    for xnVideo in xnlVideos do
        MessageBox.Show(String.Format("Last cast-members section of any video " +
                            "that has a cast-members section\n" +
                            "____________________________________________________\n{0}",
                            xnVideo.InnerXml),
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0
    
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes();    

This would produce:

The Last Child Node

Boolean Node Searching

 

AND Both Child Nodes

You may have noticed that, in our XML document, some parent nodes include some child nodes that are not found in other parent nodes. For example, the first, the second, and the third videos of our XML document have a <format> child node but the fourth video does not. On the other hand, the second, the third, and the fourth videos have a <categories> child node while the first does not. You can ask the XmlNodeList.SelectNodes() method (in fact the XML interpreter) to produce in its results only the parent nodes that have a combination of certain two nodes. To get such a result, add a first combination that includes one of the names of child nodes. Include a second pair of square brackets with the other name. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[format][categories]"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0   

This would produce:

AND Both Child Nodes

AND Both Child Nodes

The "and" operator is used to check that two child nodes are found under a parent node. To use it, create the square brackets and in them, provide the names of two child nodes separated by the and operator. Here is an example:

let xnlVideos = xeVideo.SelectNodes "//videos/video[format and rating]"

In this case, only parent nodes that have both child nodes would be produced.

OR Either Child Node

To produce the parent nodes that include one or the other child node, use the or operator. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[cast-members or categories]"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

In this case, only parent nodes that have both child nodes would be produced:

AND Both Child Nodes

Accessing the Grand-Children by Position

AND Both Child Nodes

Accessing the Nodes With Specific Grand-Children

Accessing the Nodes With Specific Grand-Children

Once you have accessed the nodes, you can apply any concept we have reviewed so far to locate a specific node. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes"/videos/video/cast-members[actor or narrator][. = 'Danny DeVito']"    

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

AND Both Child Nodes

NOT This Child Node

To let you get only the nodes that do not have a certain child node, the XPath provides a Boolean function named not. To use it, pass the name of the node to it. 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;
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos/video[not(cast-members)]");

	for xnVideo in xnlVideos do
	    MessageBox.Show(xnVideo.OuterXml,
			    "Videos with both Format and Category sections",
			    MessageBoxButtons.OK,
			    MessageBoxIcon.Information) |> ignore

	return 0;
    }
}

When the not() function returns, it produces only the nodes that don't have the child-node whose name was passed:

NOT This Child Node

NOT This Child Node

Sets Combinations

All the expressions we have seen so far produced only one result each. To let you combine two results into one, the XPath language provides the | operator. It must be applied between two expressions. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//cast-members[actor='Danny DeVito'] | //cast-members[actor='Eddie Murphy']"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0
    
	let xnlVideos : XmlNodeList = xeVideo.SelectNodes();

Boolean Operations

 

Numeric Comparisons on a Node Value

The XPath language provides some operators that can be used to perform Booleans operations. The numeric comparisons are used to find the Boolean relationship between two values. Only some operators are allowed. If you use an operator that is not valid, the compiler would throw an exception. The valid Boolean operators and the rules are:

Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//videos/video[length >= 100]"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0   

Logical Conjunctions

Logical conjunction consists of combining two Boolean operations that must both produce true results. To create a logical conjunction, create some square brackets applied to the parent name of a node and create the conjunction operation in the square brackets. There are two main ways you can perform the operation:

In the same way, you can create as many conjunctions as you want, by separating the operations with the and operator.

Logical Disjunctions

Logical disjunction consists of applying the same criterion to two nodes or applying different criteria to the same node so that at least one of the operations needs to be true. To create a logical disjunction, apply the square brackets to the parent node. As seen for the conjunction, there are two main ways to use a logical disjunction:

By using the Boolean search operators (and, or, and the not() functions) and the logical conjunction/disjunction operations, you can create tremendous combinations to include and exclude some nodes in the XPath expression and get the desired results.

XPath Axes

 

XPath Keywords

An axis is a technique of locating a node or a series of nodes using a path. To address this issue, the XPath language provides some keywords that can be used in the expressions. As we are going to see, some keywords are optional and some other keywords are necessary or useful. If you decide to include one of those keywords in your XPath expression, you must use only a valid keyword. If you use a keyword that is not recognized, the compiler will throw an XPathException exception.

When used, an axis keyword is followed by ::, followed by the name of a node or an operator.

Child Nodes

The child keyword is used to indicate that a child node must be accessed. The child keyword is followed by ::. If you want to see all child nodes, follow :: with *. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/child::*"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

That code would produce all nodes that are direct children of video. If a child node includes its own child nodes, the node and all its children would be considered as one. To get only specific child nodes, follow :: by the name of the child node to access. Here is an example that accesses the director child nodes:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(175, 50),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/child::director"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml,
                        "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

In the same way, you can access any child node by preceding it with the child keyword. In most cases, you can omit the child keyword. For example this:

let xnlVideos = xeVideo.SelectNodes ".//video/*/actor"

Is the same as:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 275),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxDirectors = new ListBox(Location = new Point(12, 12),
			       Size = new System.Drawing.Size(160, 260));
exercise.Controls.Add lbxDirectors

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes ".//video/*/child::actor"

    for xnVideo in xnlVideos do
        lbxDirectors.Items.Add xnVideo.InnerText |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

You can also apply any of the rules we have used so far. For example, the following code will produce the child nodes of the second video if the child node is named cast-members:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(200, 75),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video[2]/child::cast-members"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml,
                        "Video Collection",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Accessing Specific Nodes

Parent Nodes

The parent keyword is used to get the parent of an element. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let lbxDirectors = new ListBox(Location = new Point(12, 12),
                               Size = new System.Drawing.Size(160, 90));
exercise.Controls.Add lbxDirectors

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//parent::director"

    for xnVideo in xnlVideos do
        lbxDirectors.Items.Add xnVideo.InnerText |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

The Ancestors of a Node

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:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//ancestor::video"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

The Descendants of a Node

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

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:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "//preceding::categories"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.InnerXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

If your expression includes 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 Next Sibling of a Node

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:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos = xeVideo.SelectNodes "/videos/video/following::director"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml, "Video Collection",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This code would access the director nodes, excluding the first one.

XPath and XML Attributes

 

Introduction

As you should know already, an attribute is a type of element included in the start tag of a node. Here are examples of attributes in an XML document of a file named Videos.xml:

<?xml version="1.0" encoding="utf-8"?>
<videos common-name="Video Collection" purpose="To keep track of personal/home videos">
  <video shelf-number="CMD97904">
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video shelf-number="PLT24857">
    <title France="Monsieur le Député" Italy="Il Distinto Gentiluomo" Spain="Su Distinguida Señoría">The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <cast-members>
      <actor role="Thomas Jefferson Johnson">Eddie Murphy</actor>
      <actor role="Dick Dodge">Lane Smith</actor>
      <actor role="Miss Loretta">Sheryl Lee Ralph</actor>
      <actor role="Olaf Andersen">Joe Don Baker</actor>
      <actor role="Celia Kirby">Victoria Rowell</actor>
    </cast-members>
    <cast-members>
      <actor role="Elijah Hawkins">Charles S. Dutton</actor>
      <actor role="Arthur Reinhardt">Grant Shaud</actor>
      <actor role="Terry Corrigan">Kevin McCarthy</actor>
      <actor role="Armando">Victor Rivers</actor>
      <actor role="Homer">Chi McBride</actor>
      <actor role="Zeke Bridges">Noble Willingham</actor>
    </cast-members>
    <length>112</length>
    <format screen="Wide Screen">DVD</format>
    <rating>R</rating>
    <year-released date-released="4 December 1992">1992</year-released>
    <categories>
      <genre>Comedy</genre>
      <genre>Politics</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>government</keyword>
        <keyword>con artist</keyword>
        <keyword>lobbyist</keyword>
        <keyword>election</keyword>
      </keywords>
    </categories>
  </video>
  <video>
    <title>Duplex</title>
    <director>Danny DeVito</director>
    <cast-members>
      <narrator>Danny DeVito</narrator>
    </cast-members>
  </video>
  <video shelf-number="SCF13948">
    <title Spain="El Día de Mañana" Croatia="Dan Poslije Sutra" Portugal="O Dia Depois de Amanhã">The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124</length>
    <categories>
      <genre>Drama</genre>
      <genre>Environment</genre>
      <genre>Science Fiction</genre>
    </categories>
    <format>BD</format>
    <rating>PG-13</rating>
    <keywords>
      <keyword>climate</keyword>
      <keyword>global warming</keyword>
      <keyword>disaster</keyword>
      <keyword>new york</keyword>
    </keywords>
  </video>
  <video shelf-number="CMD93805">
    <title>Other People's Money</title>
    <director>Alan Brunstein</director>
    <year-released date-released="18 October 1991">1991</year-released>
    <cast-members>
      <actor role="Lawrence Garfield">Danny DeVito</actor>
      <actor role="Andrew Jorgenson">Gregory Peck</actor>
      <actor role="Kate Sullivan">Penelope Ann Miller</actor>
    </cast-members>
    <cast-members>
      <actor role="Bill Coles">Dean Jones</actor>
      <actor role="Bea Sullivan">Piper Laurie</actor>
    </cast-members>
    <categories>
      <genre>Comedy</genre>
      <keywords>
        <keyword>satire</keyword>
        <keyword>female stocking</keyword>
        <keyword>seduction</keyword>
      </keywords>
      <genre>Business</genre>
      <keywords>
        <keyword>capitalism</keyword>
        <keyword>corporate take-over</keyword>
        <keyword>factory</keyword>
        <keyword>speech</keyword>
        <keyword>public speaking</keyword>
      </keywords>
      <genre>Drama</genre>
      <keywords>
        <keyword>play</keyword>
        <keyword>hostile take-over</keyword>
        <keyword>corporate raider</keyword>
      </keywords>
    </categories>
  </video>
</videos>

To access an attribute, follow the name of its parent tag with a forward slash, an @ sign, and the name of the attribute. For example, if the root node has an attribute, use the formula:

/RootName/@AttributeName");

Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes("/videos/@common-name");

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml, "Video Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[]
let main argv = 
    Application.Run exercise
    0

This would produce:

Introduction to XPath and XML Attributes

In the same way, use any of the formulas we have seen so far to access any node. Then, if the node has an attribute, use the @ sign to get that attribute. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(185, 105),
                        StartPosition = FormStartPosition.CenterScreen)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos = xeVideo.SelectNodes "/videos/video/@shelf-number"

    for xnVideo in xnlVideos do
        MessageBox.Show(xnVideo.OuterXml, "Video Collection",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information) |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

 Introduction to XPath and XML Attributes    Introduction to XPath and XML Attributes

Introduction to XPath and XML Attributes    Introduction to XPath and XML Attributes

 

If you use an attribute that either doesn't exist or the element doesn't have that particular attribute, the result would be empty; no exception would be thrown.

Getting all Attributes of an Element

If you want to get all the attributes of an element, replace the name of the attribute with * as in @*. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(215, 125),
                        StartPosition = FormStartPosition.CenterScreen)

exercise.Controls.Add(new Label(Text = "Characters in Videos",
                                AutoSize = true, Location = new Point(12, 10)))
let lbxActorsRoles = new ListBox(Location = new Point(12, 28),
                                 Size = new System.Drawing.Size(188, 90))
exercise.Controls.Add(lbxActorsRoles)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos : XmlNodeList = xeVideo.SelectNodes "/videos/video/title/@*"

    for xnVideo in xnlVideos do
        lbxActorsRoles.Items.Add xnVideo.OuterXml |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Getting all Attributes of an Element

Getting the Value of an Attribute

As we have seen so far, both the XPath language and the .NET Framework provide various means to access an attribute. For example, the XPath language uses the @ sign to access an XML attribute while the XmlNode class is equipped with the OuterXml, the InnerXml, and the InnerText properties. Here is an example that uses the XmlNode.InnerXml property to access the attribute:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(205, 250),
                        StartPosition = FormStartPosition.CenterScreen)

exercise.Controls.Add(new Label(Text = "Characters in Videos",
                                AutoSize = true, Location = new Point(12, 10)))
let lbxActorsRoles = new ListBox(Location = new Point(12, 28),
                                 Size = new System.Drawing.Size(180, 220))
exercise.Controls.Add(lbxActorsRoles)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos = xeVideo.SelectNodes "/videos/video/cast-members/actor/@role"

    for xnVideo in xnlVideos do
        lbxActorsRoles.Items.Add xnVideo.InnerXml |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Getting the Value of an Attribute

Remember that, to get all attributes, you can use @* as in:

let xnlVideos = xeVideo.SelectNodes "/videos/video/cast-members/actor/@*"

for xnVideo in xnlVideos do
    lbxActorsRoles.Items.Add xnVideo.InnerXml |> ignore

Notice that the XmlNode.InnerXml property applied to an attribute produces only the text of the attribute. In the same way, you can use the XmlNode.InnerText property to get the same result. On the other hand, the XmlNode.OuterXml property produces the name and value of an attribute. Here is an example:

let xnlVideos = xeVideo.SelectNodes "/videos/video/cast-members/actor/@role"

for xnVideo in xnlVideos do
    lbxActorsRoles.Items.Add xnVideo.OuterXml |> ignore

This would produce:

Getting the Value of an Attribute

Getting an Attribute and its Parent

In some cases, you may want to get both the attribute and its parent. To do that, after the name of the element, include the @ and name of the attribute in square brackets. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(345, 255),
                        StartPosition = FormStartPosition.CenterScreen)

exercise.Controls.Add(new Label(Text = "Characters in Videos",
                                AutoSize = true, Location = new Point(12, 10)))
let lbxActorsRoles = new ListBox(Location = new Point(12, 28),
                                 Size = new System.Drawing.Size(320, 220))
exercise.Controls.Add(lbxActorsRoles)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos = xeVideo.SelectNodes "/videos/video/cast-members/actor[@role]"

    for xnVideo in xnlVideos do
        lbxActorsRoles.Items.Add xnVideo.OuterXml |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Getting an Attribute and its Parent

If you want to get all attributes and their parent, remember that you can use * in place of the name of the attribute. Here is an example:

open System
open System.IO
open System.Xml
open System.Drawing
open System.Windows.Forms

let exercise = new Form(MaximizeBox = false, Text = "Video Collection",
                        ClientSize = new System.Drawing.Size(675, 85),
                        StartPosition = FormStartPosition.CenterScreen)

exercise.Controls.Add(new Label(Text = "Characters in Videos",
                                AutoSize = true, Location = new Point(12, 10)))
let lbxActorsRoles = new ListBox(Location = new Point(12, 28),
                                 Size = new System.Drawing.Size(650, 50))
exercise.Controls.Add(lbxActorsRoles)

let strFileName = "../../Videos.xml"
let xdVideos : XmlDocument = new XmlDocument()

if File.Exists strFileName then
    use fsVideo = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
    xdVideos.Load fsVideo

    let xeVideo : XmlElement = xdVideos.DocumentElement
    let xnlVideos = xeVideo.SelectNodes "/videos/video/title[@*]"

    for xnVideo in xnlVideos do
        lbxActorsRoles.Items.Add xnVideo.OuterXml |> ignore

    fsVideo.Close()

[<EntryPoint>]
let main argv = 
    Application.Run exercise
    0

This would produce:

Getting an Attribute and its Parent


Home Copyright © 2014-2015 FunctionX, Inc. Home