Home

Introduction

 

Fundamentals

 

Introduction

 

 

     
 
 

 

   
   
 

Previous Copyright © 2015 FunctionX Next

Home

XML in F#: The Attributes of an XML Element

 

Fundamentals of Attributes

 

Introduction

When studying XML elements we saw how they constituted the main objects of an XML document. We also saw that an element could be nested inside of another element. Instead of nesting an element, you can transform the nested element into being part of the nesting element and thereby giving away its element qualities. This is the basis of an attribute.

An attribute is a value that is created as part of an element, making that value different from the value of a regular element. There are similarities and differences between an element and an attribute.

The element and the attribute have these in common:

The differences between an element and an attribute are:

To support attributes, the .NET Framework provides a class named XmlAttribute that is derived from XmlNode:

type XmlAttribute =  
    class 
        inherit XmlNode 
    end

Creating an Attribute

Imagine you have an ISBN element as a child of a Video element as follows:

<video>
  <ISBN>0-7888-1623-3</ISBN>
</video>

An attribute must be created inside the start-tag of an element. To manually create an attribute, type the left angle bracket of the element, followed by the name of the element, an empty space, and the name of the attribute. The name follows the same rules we defined for names in XML.

An attribute should have a value that can be used to distinguish it. To specify the name of an attribute, assign a value as a string to its name. In the case of the above code fragment, since ISBN is simply a child of the video element, you can change the ISBN element to become an attribute of the video element as follows:

<video ISBN="0-7888-1623-3">

Now, ISBN is an attribute of the video element.

The Collection of Attributes of an Element

 

Introduction

An element can have many different attributes. Here is an example:

<video ISBN="0-7888-1623-3" ScreenRatio="Standard" SoundtrackAvailable="True" />

The attributes of an element are stored in a collection named XmlAttributeCollection. To support attributes, the XmlElement class is equipped with a property named Attributes:

abstract Attributes : XmlAttributeCollection with get 
override Attributes : XmlAttributeCollection with get

Here is an example of accessing the attributes of an element:

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

let exercise = new Form(MaximizeBox = false, Text = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnAttribute = new Button(Text = "Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreeateAttribute

let btnAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xnlAutoParts : XmlNodeList = xdAutoParts.GetElementsByTagName "auto-part"

        for i in 0 .. xnlAutoParts.Count - 1 do
            for xaPart in xnlAutoParts.[i].Attributes do
            
                . . .

        fsAutoParts.Close()

btnCreateAttribute.Click.Add btnCreateAttributeClick

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

The Number of Attributes in an Element

To know the number of attributes in an element, you can use the XmlNamedNodeMap.Count property:

abstract Count : int with get
override Count : int with get

Accessing an XML Attribute

To access an attribute by its position in the collection, you can use the XmlNamedNodeMap.Item() method:

abstract Item :
        index : int -> XmlNode  
override Item :
        index : int -> XmlNode

The XmlAttributeCollection class is equipped with an ItemOf indexed property. This property is overloaded in three versions. The first version has the following signature:

member ItemOf :
        i : int -> XmlAttribute with get

This property allows you to access an attribute by considering that the attributes are stored in an array. The first or most left attribute has an index of 0; the second attribute from left (of course without counting the name of the element) has an index of 1, and so on.

It can be difficult and sometimes unpredictable, in some scenarios, to access an attribute by its index because you must know exactly where each attribute is positioned. Consider the following version of our Videos.xml XML file:

<?xml version="1.0" encoding="utf-8" ?>
<videos FileDesc="Personal Video Collection">
    <video ISBN="0-7888-1623-3"
	   ScreenRatio="Standard"
	   SoundtrackAvailable="True">
        <title StoryBy="Marty Kaplan and Jonathan Reynold"
	       Screenplay="Marty Kaplan">The Distinguished Gentleman</title>
        <director>Jonathan Lynn</director>
        <actors></actors>
        <length>112 Minutes</length>
        <format>DVD</format>
        <rating>R</rating>
    </video>
    <video ISBN="0-7907-3900-3">
        <title Screenplay="Charlie Peter">Her Alibi</title>
        <director>Bruce Beresford</director>
        <length>94 Mins</length>
        <format>DVD</format>
        <rating>PG-13</rating>
    </video>
</videos>

In the first video, the name of the screenplay writer is stored at index 1. In the second video, the name of the screenplay writer is stored at index 0. In this case, it may not be a good item to use the index to locate an attribute. Fortunately, the second version of the overloaded XmlAttributeCollection.ItemOf[] property has the following signature:

member ItemOf : 
        name : string -> XmlAttribute with get

With this version, you can explicitly specify the name of the attribute that you want.

The Inner Text of an Attribute

In the .NET Framework, an attribute is represented by the XmlAttribute class. Like all nodes, this class is based on the XmlNode class. The name of an attribute is represented by its (read-only) Name property. The value of an attribute is represented by its Value property. Besides Value, you can also use XmlAttribute.InnerText or XmlAttribute.InnerXml to access the text of an attribute.

Getting a Reference to an Attribute

 

Getting an Attribute as a Node

Many operations require that you get a reference to an attribute before proceeding. To assist you with this, the XmlElement class has a method named GetAttributeNode. Its signature is:

abstract GetAttributeNode : 
        name:string -> XmlAttribute  
override GetAttributeNode : 
        name:string -> XmlAttribute

Consider the following AutoParts.xml file:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part item-number="937418">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="LE" engine="1.8L L4" body-style="4-Speed Automatic Transaxle U341E">Corolla</model>
    <category>Shocks, Struts &amp; Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price status="New">58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price status="Refurbished">44.45</unit-price>
  </auto-part>
  <auto-part item-number="580686">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="SE" engine="2.0L L4 Gas" body-style="6-Speed Automatic Transaxle 6F">Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price status="New">14.15</unit-price>
  </auto-part>
</auto-parts>

Here is an example of calling this method:

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

let exercise = new Form(MaximizeBox = false, Text = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnGetAttribute = new Button(Text = "Get Attribute",
                                  Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnGetAttribute

let btnGetAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xaBusiness : XmlAttribute = xdAutoParts.DocumentElement.GetAttributeNode "business"

        MessageBox.Show("Attribute Name = " + xaBusiness.Name + ", Value = " + xaBusiness.Value,
                        "College Park Auto-Parts", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
btnGetAttribute.Click.Add btnGetAttributeClick

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

Here is an example of running the program:

Getting a Reference to an Attribute

Getting an Attribute from an Element

Remember that the attributes of an element are stored in a collection. You can use that collection to locate a node, access their attributes, and then get a reference to the desired 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 = "Time Zones",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnGetAttribute = new Button(Text = "Has Attributes",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnGetAttribute

let btnGetAttributeClick _ =
    let strFileName = "..\..\TimeZones.xml"
    let xdTimeZones : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsTimeZones = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdTimeZones.Load fsTimeZones
        fsTimeZones.Close()
        
        // Get a list of elements whose names are "name"
        let xnlTimeZones : XmlNodeList = xdTimeZones.GetElementsByTagName "name"
        
        // Visit each time zone element
        for xnTimeZone in xnlTimeZones do
            // Look for a time zone named Eastern Standard Time
            if xnTimeZone.InnerText = "Eastern Standard Time" then
                // Get a list of the third siblings of that node. This represents the states
                let xnlStates : XmlNodeList = xnTimeZone.NextSibling.NextSibling.ChildNodes;
                
                // Visit each state
                for xnState in xnlStates do
                    // Look for a state named Florida
                    if xnState.InnerText = "Florida" then
                        // Get its attributes
                        for xaCharacteristics in xnState.Attributes do
                            MessageBox.Show("Attribute: Name = " + xaCharacteristics.Name + ", Value: " + xaCharacteristics.Value,
                                            "Time Zones", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
btnGetAttribute.Click.Add btnGetAttributeClick

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

Operations on an XML Attribute

 

Checking Whether an Element Has Attributes

To let you find out whether an element has at least one attribute, the XmlElement class is equipped with a method named HasAttributes. Its signature is:

abstract HasAttributes : bool with get 
override HasAttributes : bool with get

Consider the following XML file named TimeZones.xml:

<?xml version="1.0" encoding="utf-8" ?>
<roads>
  <road>
    <road-name length-rank="1">I-90</road-name>
    <road-type>Interstate</road-type>
    <distance km="4861.09">3020.54</distance>
    <location>From the Edgar Martinez Drv South to Boston, MA</location>
    <intersections>
      <intersection>
        <intersecting>SR 519</intersecting>
        <in-near>Seattle, WA</in-near>
      </intersection>
      <intersection>
        <intersecting>I-5</intersecting>
        <in-near>Seattle, WA</in-near>
      </intersection>
    </intersections>
  </road>
  <road>
    <road-name length-rank="4">I-10</road-name>
    <road-type>Interstate</road-type>
    <distance km="3959.53">2460.34</distance>
    <location>From SR-1 (California State Route 1) to I-95 in Jacksonville, FL</location>
    <intersections>
      <intersection>
        <intersecting>SR 1</intersecting>
        <in-near>Santa Monica, CA</in-near>
      </intersection>
      <intersection>
        <intersecting>I-5</intersecting>
        <in-near>Los Angeles, CA</in-near>
      </intersection>
    </intersections>
  </road>
</roads>

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 = "Road Database",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnHasAttributes = new Button(Text = "Has Attributes",
                                  Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnHasAttributes

let btnHasAttributesClick _ =
    let strFileName = "..\..\Roads1.xml"
    let xdRoads : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsRoads = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdRoads.Load fsRoads
        fsRoads.Close()
        
        // Get a list of elements whose names are "road-name"
        let mutable xnlRoads : XmlNodeList = xdRoads.GetElementsByTagName "road-name"
        
        // Visit each road element
        for xnRoad in xnlRoads do
            // Look for a road named I-10
            if xnRoad.InnerText = "I-10" then
                if(xnRoad :?> XmlElement).HasAttributes = true then
                    MessageBox.Show("Road " + xnRoad.InnerText + " has at least one attribute.",
                                    "Road Database", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
                else
                    MessageBox.Show("Road " + xnRoad.InnerText + " ain't got no attribute(s).",
                                    "Road Database", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore

                if(xnRoad.NextSibling :?> XmlElement).HasAttributes = true then
                    MessageBox.Show("Road Type " + xnRoad.NextSibling.InnerText + " has at least one attribute.",
                                    "Road Database", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
                else
                    MessageBox.Show("Road Type " + xnRoad.NextSibling.InnerText + " ain't got no attribute(s).",
                                    "Road Database", MessageBoxButtons.OK, MessageBoxIcon.Information) |> ignore
btnHasAttributes.Click.Add btnHasAttributesClick

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

Here is an example of running the program:

Checking Whether an Element Has Attributes Checking Whether an Element Has Attributes

 

Manually Creating an Attribute

An element can have 0, one, or more attributes. The attributes of an element are stored in the Attributes property of an XmlElement object. The XmlElement.Attributes property is based on a class called XmlAttributeCollection. The XmlAttributeCollection class is based on the XmlNamedNodeMap class.

Before performing an attribute-related operation on an element, to find out whether the element has any attribute, you can check the value of the Boolean HasAttributes property of its XmlElement element. If this property produces a true value, then the element has at least one attribute; otherwise, the element doesn't have any.

While a certain element may have an attribute, a sibling element with the same name may not have an attribute or may have a completely different type of attribute. Here is an XML file with attributes in some elements:

<?xml version="1.0" encoding="utf-8" ?>
<videos>
    <video ISBN="0-7888-1623-3">
	<title Screenplay="Marty Kaplan">The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<length>112 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
    </video>
    <video>
	<title WrittenBy="Charlie Peter">Her Alibi</title>
	<director>Bruce Beresford</director>
	<length>94 Mins</length>
	<format>DVD</format>
	<rating>PG-13</rating>
    </video>
</videos>

Remember that you can include white spaces to make your code easy to read. This means that you can type an attribute on the next line of its element's name. We know that every element must be closed. We saw that we could close an element with an end-tag as follows:

<video><ISBN>0-7888-1623-3</ISBN></video>

We also saw that we could close an element locally as follows: <video />. If you create an attribute in an empty element, you can also close it by typing the indicative forward slash before the right angle bracket and after an empty space. Here is an example:

<video ISBN="0-7888-1623-3" />

Setting an Attribute by Name and Value

As mentioned already, an attribute primarily belongs to an element. This means that, when creating an attribute, you must specify what element it would belong to. To support the attributes of an element, the XmlElement class is equipped with the SetAttribute() method which is overloaded in two versions. The first version of this method uses the following signatur:

abstract SetAttribute : 
        name:string * 
        value:string -> unit  
override SetAttribute : 
        name:string * 
        value:string -> unit

The first argument is the name of the new attribute and the second argument will be its text. Before adding an attribute, you should first identify its parent element. Consider the following file named AutoParts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<auto-parts>
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Shocks, Struts & Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price>58.85</unit-price>
  </auto-part>
  <auto-part>
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price>44.45</unit-price>
  </auto-part>
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price>14.15</unit-price>
  </auto-part>
</auto-parts>

Here is an example that adds an attribute to the root element:

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

let exercise = new Form(MaximizeBox = false, Text = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnSetAttribute = new Button(Text = "Set Attribute",
                                 Location = new Point(12, 12), Width = 100)
exercise.Controls.Add btnSetAttribute

let btnSetAttributeClick _ =
    let strFileName = "..\..\AutoParts1.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

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

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)

        // Create an attribute and add it to the root element
        xdAutoParts.DocumentElement.SetAttribute("business", "College Park Auto-Parts")

        // Save the file
        xdAutoParts.Save fsAutoParts

        fsAutoParts.Close()

btnSetAttribute.Click.Add btnSetAttributeClick

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

From the above file, this code would result in:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Shocks, Struts & Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price>58.85</unit-price>
  </auto-part>
  <auto-part>
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price>44.45</unit-price>
  </auto-part>
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price>14.15</unit-price>
  </auto-part>
</auto-parts>

Creating an Attribute

To support attribute addition, the XmlDocument class is equipped with the CreateAttribute() method, which is overloaded in three versions. The first version of this method has the following signatur:

member CreateAttribute : 
        name : string -> XmlAttribute

This method expects the name of the attribute as argument. If it succeeds, this method produces an XmlAttribute object.

Adding Many Attributes to an Element

To let you add a new attribute to an element, the XmlElement class is equipped with a method named SetAttributeNote. This method is overloaded with two versions. One of the versions uses the following signatur:

abstract SetAttributeNode : 
        newAttr:XmlAttribute -> XmlAttribute  
override SetAttributeNode : 
        newAttr:XmlAttribute -> XmlAttribute

This method expects an XmlAttribute object. Here is an example that looks for a particular node in a collection and adds an attribute to it:

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

let exercise = new Form(MaximizeBox = false, Text = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreeateAttribute = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreeateAttribute

let btnCreeateAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

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

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)

        // Create an attribute
        let xaItemNumber : XmlAttribute = xdAutoParts.CreateAttribute "item-number"
        xaItemNumber.Value <- "280486"
        
        // Get a list of elements whose names are "year"
        let xnlYears : XmlNodeList = xdAutoParts.GetElementsByTagName "year"
        
        // Visit each auto part element
        for i in 0 ..  xnlYears.Count - 1 do
            // Look for an auto part that has the year 2015
            if xnlYears.[i].InnerText = "2015" then
                // Once you find that auto-part, add the new attribute to it
                (xnlYears.[i].ParentNode :?> XmlElement).SetAttributeNode xaItemNumber |> ignore

        // Save the file
        xdAutoParts.Save fsAutoParts

        fsAutoParts.Close()

btnCreeateAttribute.Click.Add btnCreeateAttributeClick

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

From the above file, this code would result in:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Shocks, Struts & Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price>58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price>44.45</unit-price>
  </auto-part>
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price>14.15</unit-price>
  </auto-part>
</auto-parts>

You might have noticed that the above code made a comparison on the value of only one element, and that type of value (of the year element) is used by more than one element (year = 2012). If you perform the same comparison on a value that is repeated, you would receive an error. 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 = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreeateAttribute = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreeateAttribute

let btnCreeateAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

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

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)

        // Create an attribute
        let xaItemNumber : XmlAttribute = xdAutoParts.CreateAttribute "item-number"
        xaItemNumber.Value <- "580686"
        
        // Get a list of elements whose names are "year"
        let xnlYears : XmlNodeList = xdAutoParts.GetElementsByTagName "year"
        
        // Visit each auto part element
        for i in 0 ..  xnlYears.Count - 1 do
            // Look for an auto part that has the year 2015
            if xnlYears.[i].InnerText = "2012" then
                // Once you find that auto-part, add the new attribute to it
                (xnlYears.[i].ParentNode :?> XmlElement).SetAttributeNode xaItemNumber |> ignore

        // Save the file
        xdAutoParts.Save fsAutoParts

        fsAutoParts.Close()

btnCreeateAttribute.Click.Add btnCreeateAttributeClick

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

This code would produce an error:

Adding an Attribute to an Element

An unprofessional solution is to perform the comparison on all or other values of the same 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 = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreateAttribute = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreeateAttribute

let btnCreateAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

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

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)

        // Create an attribute
        let xaItemNumber : XmlAttribute = xdAutoParts.CreateAttribute "item-number"
        xaItemNumber.Value <- "580686"
        
        // Get a list of elements whose names are "year"
        let xnlYears : XmlNodeList = xdAutoParts.GetElementsByTagName "year"
        
        // Visit each auto part element
        for i in 0 ..  xnlYears.Count - 1 do
            // Look for an auto part that has the year 2015
            if( (xnlYears.[i].InnerText = "2012") &&
                (xnlYears.[i].NextSibling.InnerText = "Toyota") &&
                (xnlYears.[i].NextSibling.NextSibling.InnerText = "Corolla") &&
                (xnlYears.[i].NextSibling.NextSibling.NextSibling.InnerText = "Air Filters") &&
                (xnlYears.[i].NextSibling.NextSibling.NextSibling.NextSibling.InnerText = "FRAM CF10285 Fresh Breeze Cabin Air Filter") ) then
                // Once you find that auto-part, add the new attribute to it
                (xnlYears.[i].ParentNode :?> XmlElement).SetAttributeNode xaItemNumber |> ignore

        // Save the file
        xdAutoParts.Save fsAutoParts

        fsAutoParts.Close()

btnCreateAttribute.Click.Add btnCreateAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part>
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Shocks, Struts & Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price>58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price>44.45</unit-price>
  </auto-part>
  <auto-part item-number="580686">
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price>14.15</unit-price>
  </auto-part>
</auto-parts>

We referred to this solution because there is no guaranty that two elements cannot have the exact same characteristics (same car make, same model, same year, same part name). The better solution used in databases is to give a unique characteristic, sometimes called a unique key, to each record. For our auto-parts application, this would corresponding to giving a unique item number to each auto part.

By using the collection of attributes of an element, you can locate an attribute in an element and take an appropriate action, such as adding an attribute to a sibling 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 = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreateAttribute = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreateAttribute

let btnCreateAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xnlAutoParts : XmlNodeList = xdAutoParts.GetElementsByTagName "auto-part"

        for i in 0 .. xnlAutoParts.Count - 1 do
            for xaPart in xnlAutoParts.[i].Attributes do
                if (xaPart.Name = "item-number") && (xaPart.Value="937418") then
                    // Create an attribute
                    let xaTrim : XmlAttribute = xdAutoParts.CreateAttribute "trim"
                    xaTrim.Value <- "LE"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaTrim |> ignore
       
                    use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                    xdAutoParts.Save fsAutoParts
        	    fsAutoParts.Close()

btnCreateAttribute.Click.Add btnCreateAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part item-number="937418">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="LE">Corolla</model>
    <category>Shocks, Struts &amp; Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price>58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price>44.45</unit-price>
  </auto-part>
  <auto-part item-number="580686">
    <year>2012</year>
    <make>Toyota</make>
    <model>Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price>14.15</unit-price>
  </auto-part>
</auto-parts>

Adding Many Attributes

In the same, you can create as many attributes as you want. Here are examples:

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

let exercise = new Form(MaximizeBox = false, Text = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreateAttributes = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreateAttribute

let btnCreateAttributesClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let mutable xaNewPart : XmlAttribute = null
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xnlAutoParts : XmlNodeList = xdAutoParts.GetElementsByTagName "auto-part"

        for i in 0 .. xnlAutoParts.Count - 1 do
            for xaPart in xnlAutoParts.[i].Attributes do
                // New Attribute
                xaNewPart <- xdAutoParts.CreateAttribute "status"
                xaNewPart.Value <- "New"
                (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore

                if (xaPart.Name = "item-number") && (xaPart.Value="937418") then
                    // New Attribute
                    xaNewPart <- xdAutoParts.CreateAttribute "engine"
                    xaNewPart.Value <- "1.8L L4"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore
       
                    // New Attribute
                    xaNewPart <- xdAutoParts.CreateAttribute "body-style"
                    xaNewPart.Value <- "4-Speed Automatic Transaxle U341E"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore
                    
                if (xaPart.Name = "item-number") && (xaPart.Value="580686") then
                    // New Attribute
                    xaNewPart <- xdAutoParts.CreateAttribute "trim"
                    xaNewPart.Value <- "SE"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore

                    // New Attribute
                    xaNewPart <- xdAutoParts.CreateAttribute "engine"
                    xaNewPart.Value <- "2.0L L4 Gas"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore
       
                    // New Attribute
                    xaNewPart <- xdAutoParts.CreateAttribute "body-style"
                    xaNewPart.Value <- "6-Speed Automatic Transaxle 6F"
                    (xnlAutoParts.[i].FirstChild.NextSibling.NextSibling :?> XmlElement).SetAttributeNode xaNewPart |> ignore

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
        xdAutoParts.Save fsAutoParts
        fsAutoParts.Close()

btnCreateAttributes.Click.Add btnCreateAttributesClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part item-number="937418">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="LE" engine="1.8L L4" body-style="4-Speed Automatic Transaxle U341E">Corolla</model>
    <category>Shocks, Struts &amp; Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price status="New">58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price status="New">44.45</unit-price>
  </auto-part>
  <auto-part item-number="580686">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="SE" engine="2.0L L4 Gas" body-style="6-Speed Automatic Transaxle 6F">Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price status="New">14.15</unit-price>
  </auto-part>
</auto-parts>

Appending an Attribute

Appending an attribute consists of adding an attribute to an element. Imagine the element already has at least one attribute:

<?xml version="1.0" encoding="utf-8"?>
<periodic-table>
  <element>
    <atomic-number>1</atomic-number>
    <name>Hydrogen</name>
    <symbol>H</symbol>
    <atomic-mass>1.0079</atomic-mass>
  </element>
  <element>
    <atomic-number column="18">2</atomic-number>
    <name>Helium</name>
    <symbol>He</symbol>
    <atomic-mass>4.002682</atomic-mass>
  </element>
</periodic-table>

In this case, the new one is positioned to the end of the collection of the attributes of the element. To support this operation, the XmlAttributeCollection class is equipped with a method named Append. Its signature is:

member Append : 
        node:XmlAttribute -> XmlAttribute

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 = "Chemistry",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnCreateAttributes = new Button(Text = "Create Attribute",
                                 Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnCreateAttributes

let btnCreateAttributesClick _ =
    let strFileName = "..\..\PeriodicTable.xml"
    let xdPeriodicTable : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsPeriodicTable = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdPeriodicTable.Load fsPeriodicTable
        fsPeriodicTable.Close()
        
        // New Attribute
        let xaElement : XmlAttribute = xdPeriodicTable.CreateAttribute "row"
        xaElement.Value <- "1"
        let xnlElements : XmlNodeList = xdPeriodicTable.GetElementsByTagName "atomic-number"

        for xnElement in xnlElements do
            if xnElement.InnerText = "2" then
                xnElement.Attributes.Append xaElement |> ignore

        use fsPeriodicTable = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                    
        // Save the file
        xdPeriodicTable.Save fsPeriodicTable

        fsPeriodicTable.Close()
btnCreateAttributes.Click.Add btnCreateAttributesClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<periodic-table>
  <element>
    <atomic-number>1</atomic-number>
    <name>Hydrogen</name>
    <symbol>H</symbol>
    <atomic-mass>1.0079</atomic-mass>
  </element>
  <element>
    <atomic-number column="18" row="1">2</atomic-number>
    <name>Helium</name>
    <symbol>He</symbol>
    <atomic-mass>4.002682</atomic-mass>
  </element>
</periodic-table>

If the element doesn't have any attribute(s), the new one is created as the only one.

Prepending an Attribute

Prepending an attribute consists of adding a new attribute to an element. If the element doesn't have any attribute yet, the new attribute is created as the only one. If the element already has at least one attribute, the new one is positioned at the beginning of the collection. To support this operation, the XmlAttributeCollection class is equipped with a method named Prepend. Its signature is:

member Prepend : 
        node:XmlAttribute -> XmlAttribute

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 = "Chemistry",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnAppendAttribute = new Button(Text = "Append Attribute",
                                    Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnAppendAttribute

let btnPrependAttribute = new Button(Text = "Prepend Attribute",
                                     Location = new Point(12, 42), Width = 120)
exercise.Controls.Add btnPrependAttribute

let btnAppendAttributeClick _ =
    let strFileName = "..\..\PeriodicTable.xml"
    let xdPeriodicTable : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsPeriodicTable = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdPeriodicTable.Load fsPeriodicTable
        fsPeriodicTable.Close()
        
        // New Attribute
        let xaElement : XmlAttribute = xdPeriodicTable.CreateAttribute "row"
        xaElement.Value <- "1"
        let xnlElements : XmlNodeList = xdPeriodicTable.GetElementsByTagName "atomic-number"

        for xnElement in xnlElements do
            if xnElement.InnerText = "1" then
                xnElement.Attributes.Append xaElement |> ignore

        use fsPeriodicTable = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
        xdPeriodicTable.Save fsPeriodicTable
        fsPeriodicTable.Close()
btnAppendAttribute.Click.Add btnAppendAttributeClick

let btnPrependAttributeClick _ =
    let strFileName = "..\..\PeriodicTable.xml"
    let xdPeriodicTable : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsPeriodicTable = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdPeriodicTable.Load fsPeriodicTable
        fsPeriodicTable.Close()
        
        // New Attribute
        let xaElement : XmlAttribute = xdPeriodicTable.CreateAttribute "column"
        xaElement.Value <- "1"
        let xnlElements : XmlNodeList = xdPeriodicTable.GetElementsByTagName "atomic-number"

        for xnElement in xnlElements do
            if xnElement.InnerText = "1" then
                xnElement.Attributes.Prepend xaElement |> ignore

        use fsPeriodicTable = new FileStream(strFileName, FileMode.Create, FileAccess.Write) 
        xdPeriodicTable.Save fsPeriodicTable
        fsPeriodicTable.Close()
btnPrependAttribute.Click.Add btnPrependAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<periodic-table>
  <element>
    <atomic-number column="1" row="1">1</atomic-number>
    <name>Hydrogen</name>
    <symbol>H</symbol>
    <atomic-mass>1.0079</atomic-mass>
  </element>
  <element>
    <atomic-number column="18" row="1">2</atomic-number>
    <name>Helium</name>
    <symbol>He</symbol>
    <atomic-mass>4.002682</atomic-mass>
  </element>
</periodic-table>

Inserting an Attribute

To create a new attribute before it, you can call the XmlAttributeCollection.InsertBefore() method. Its signatur is:

member InsertBefore : 
        newNode:XmlAttribute * 
        refNode:XmlAttribute -> XmlAttribute

To add a new attribute after the current one, you can call the XmlAttributeCollection.InsertAfter() method. Its signatur is:

member InsertAfter :
        newNode:XmlAttribute *
        refNode:XmlAttribute -> XmlAttribute

The Parent of an Attribute

Once an attribute has been created, to identify the element to which it belongs, you can access its XmlAttribute.OwnerElement property. This property produces an XmlElement value:

abstract OwnerElement : XmlElement with get 
override OwnerElement : XmlElement with get

Editing/Updating an Attribute

Editing or updating an attribute consists of changing something about it, such as its value. You have many options.

To edit or update an attribute, you can start by locating it. This time too, you have many options. The classic way is to use a series of loops to navige both the elements and their attributes to locate the particular attribute you want. Here is an example:

let btnEditAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let mutable xaNewPart : XmlAttribute = null
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xnlAutoParts : XmlNodeList = xdAutoParts.GetElementsByTagName "auto-part"
            
        for i in 0 .. xnlAutoParts.Count - 1 do
            for xaPart in xnlAutoParts.[i].Attributes do
                if (xaPart.Name = "item-number") && (xaPart.Value="280486") then
                    let xnlUnitPrices : XmlNodeList = xnlAutoParts.[i].ChildNodes
                
                    for xnUnitPrice in xnlUnitPrices do
                        if xnUnitPrice.Name = "unit-price" then
                            for xaStatus in xnUnitPrice.Attributes do
                                if xaStatus.Name = "status" then

After accessing the attribute, you can manipulate it as you see fit. For example, you can change its value. 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 = "College Park Auto-Parts",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnEditAttribute = new Button(Text = "Edit/UPdate an Attribute",
                                 Location = new Point(12, 12), Width = 150)
exercise.Controls.Add btnEditAttribute

let btnEditAttributeClick _ =
    let strFileName = "..\..\AutoParts.xml"
    let mutable xaNewPart : XmlAttribute = null
    let xdAutoParts : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsAutoParts = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdAutoParts.Load fsAutoParts
        fsAutoParts.Close()
        
        let xnlAutoParts : XmlNodeList = xdAutoParts.GetElementsByTagName "auto-part"
            
        for i in 0 .. xnlAutoParts.Count - 1 do
            for xaPart in xnlAutoParts.[i].Attributes do
                if (xaPart.Name = "item-number") && (xaPart.Value="280486") then
                    let xnlUnitPrices : XmlNodeList = xnlAutoParts.[i].ChildNodes
                
                    for xnUnitPrice in xnlUnitPrices do
                        if xnUnitPrice.Name = "unit-price" then
                            for xaStatus in xnUnitPrice.Attributes do
                                if xaStatus.Name = "status" then
                                    xaStatus.InnerText <- "Refurbished"

        use fsAutoParts = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                    
        // Save the file
        xdAutoParts.Save fsAutoParts

        fsAutoParts.Close()

btnEditAttribute.Click.Add btnEditAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<auto-parts business="College Park Auto-Parts">
  <auto-part item-number="937418">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="LE" engine="1.8L L4" body-style="4-Speed Automatic Transaxle U341E">Corolla</model>
    <category>Shocks, Struts &amp; Suspension</category>
    <part-name>KYB SM5215 Strut mount</part-name>
    <unit-price status="New">58.85</unit-price>
  </auto-part>
  <auto-part item-number="280486">
    <year>2015</year>
    <make>Ford</make>
    <model>Escape</model>
    <category>Brake System</category>
    <part-name>Power Stop (16-1044) Z16 Ceramic Brake Pad</part-name>
    <unit-price status="Refurbished">44.45</unit-price>
  </auto-part>
  <auto-part item-number="580686">
    <year>2012</year>
    <make>Toyota</make>
    <model trim="SE" engine="2.0L L4 Gas" body-style="6-Speed Automatic Transaxle 6F">Corolla</model>
    <category>Air Filters</category>
    <part-name>FRAM CF10285 Fresh Breeze Cabin Air Filter</part-name>
    <unit-price status="New">14.15</unit-price>
  </auto-part>
</auto-parts>

Removing Attributes

 

Deleting an Attribute by its Name

If an element has an attribute you don't want or that you don't need anymore, you can delete that attribute. You have various options, two are available through the XmlElement class.

Using the XmlElement.RemoveAttributeAt() method to delete an attribute can be uncertain because you would not know whether there is an attribute at the specified position. An alternative is to specify the name of the attribute you want to delete. To support this, the XmlElement class is equipped with the RemoveAttribute() method, which is overloaded with two versions. One of the versions of this method uses the following signature:

abstract RemoveAttribute :
        name : string -> unit
override RemoveAttribute :
        name : string -> unit

This method expects as argument the name of the attribute to remove. Consider the following file named TimeZones.xml:

<?xml version="1.0" encoding="utf-8" ?>
<time-zones>
  <zone>
    <name initials="CST">Central Standard Time</name>
    <utc>-06:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="West South Central" bea-region="Southeast">Arkansas</state>
      <state inclusion="Split" cb-region="South Atlantic" bea-region="Southeast">Florida</state>
      <state inclusion="Entirely" cb-region="West North Central" bea-region="Plains">Minnesota</state>
      <state inclusion="Entirely" cb-region="East North Central" bea-region="Great Lakes">Ohio</state>
    </states-and-territories>
  </zone>
  <zone>
    <name initials="EST">Eastern Standard Time</name>
    <utc>-05:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="New England" bea-region="New England">Maine</state>
      <state inclusion="Entirely" cb-region="New England" bea-region="New England">Vermont</state>
      <state inclusion="Split" cb-region="South Atlantic" bea-region="Southeast">Florida</state>
    </states-and-territories>
  </zone>
</time-zones>

Here is an example of calling this method:

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

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

let btnRemoveAttribute = new Button(Text = "Delete Attribute",
                                  Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnRemoveAttribute

let btnRemoveAttributeClick _ =
    let strFileName = "..\..\TimeZones.xml"
    let xdTimeZones : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsTimeZones = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdTimeZones.Load fsTimeZones
        fsTimeZones.Close()
        
        // Get a list of elements whose names are "name"
        let xnlTimeZones : XmlNodeList = xdTimeZones.GetElementsByTagName "name"
        
        try
            // Visit each time zone element
            for xnTimeZone in xnlTimeZones do
                // Look for a time zone named Eastern Standard Time
                if xnTimeZone.InnerText = "Eastern Standard Time" then
                    // Get a list of the third siblings of that node. This represents the states
                    let xnlStates : XmlNodeList = xnTimeZone.NextSibling.NextSibling.ChildNodes

                    // Visit each state
                    for xnState in xnlStates do
                        // Look for a state named Florida
                        if xnState.InnerText = "Florida" then
                            // Get its attributes
                            for xaCharacteristics in xnState.Attributes do
                                if xaCharacteristics.Name = "cb-region" then
                                    (xnState :?> XmlElement).RemoveAttribute "cb-region"

                                    use fsTimeZones = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                                    xdTimeZones.Save fsTimeZones
                                    fsTimeZones.Close()
        with
        | :? InvalidOperationException as ioe -> ()

btnRemoveAttribute.Click.Add btnRemoveAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<time-zones>
  <zone>
    <name initials="CST">Central Standard Time</name>
    <utc>-06:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="West South Central" bea-region="Southeast">Arkansas</state>
      <state inclusion="Split" cb-region="South Atlantic" bea-region="Southeast">Florida</state>
      <state inclusion="Entirely" cb-region="West North Central" bea-region="Plains">Minnesota</state>
      <state inclusion="Entirely" cb-region="East North Central" bea-region="Great Lakes">Ohio</state>
    </states-and-territories>
  </zone>
  <zone>
    <name initials="EST">Eastern Standard Time</name>
    <utc>-05:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="New England" bea-region="New England">Maine</state>
      <state inclusion="Entirely" cb-region="New England" bea-region="New England">Vermont</state>
      <state inclusion="Split" bea-region="Southeast">Florida</state>
    </states-and-territories>
  </zone>
</time-zones>

Removing an Attribute by Position

The attributes of an XmlElement object are considered stored in an indexed list with the most left attribute at index 0, the second from left at index 1, and so on. Based on this, to remove an attribute by locating it based on its index, you can call the XmlElement.RemoveAttributeAt() method. Its signature is:

abstract RemoveAttributeAt :
        i : int -> XmlNode  
override RemoveAttributeAt :
        i : int -> XmlNode

When calling this method, if an attribute exists at position i, it will be deleted and the method would return it. If there is no attribute at that index, the method doesn't do anything and it returns 0.

Using the list of attributes of an element, you can delete one or all attributes of an element. Since the attributes are stored in a collection, you can locate the undesired attribute by its index and then delete it. To do this, you can call the XmlAttributeCollection.RemoveAt() method. Its signature is:

member RemoveAt :
        i : int -> XmlAttribute

This method expects the index of the attribute that needs to be removed. As mentioned for the XmlAttributeCollection.ItemOf indexed property, to efficiently use this RemoveAt() method, you should know the exact index of the attribute, otherwise, you may access and therefore delete the wrong 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 = "Time Zones",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnRemoveAttribute = new Button(Text = "Delete Attribute",
                                  Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnRemoveAttribute

let btnRemoveAttributeClick _ =
    let strFileName = "..\..\TimeZones.xml"
    let xdTimeZones : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsTimeZones = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdTimeZones.Load fsTimeZones
        fsTimeZones.Close()
        
        // Get a list of elements whose names are "name"
        let xnlTimeZones : XmlNodeList = xdTimeZones.GetElementsByTagName "name"
        
        try
            // Visit each time zone element
            for xnTimeZone in xnlTimeZones do
                // Look for a time zone named Eastern Standard Time
                if xnTimeZone.InnerText = "Eastern Standard Time" then
                    // Get a list of the third siblings of that node. This represents the states
                    let xnlStates : XmlNodeList = xnTimeZone.NextSibling.NextSibling.ChildNodes

                    // Visit each state
                    for xnState in xnlStates do
                        // Look for a state named Maine
                        if xnState.InnerText = "Maine" then
                            // Get its attributes
                            for i in 0 .. xnState.Attributes.Count - 1 do
                                if xnState.Attributes.[i].Name = "bea-region" then
                                    (xnState :?> XmlElement).RemoveAttributeAt(i) |> ignore

                                    use fsTimeZones = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                                    xdTimeZones.Save fsTimeZones
                                    fsTimeZones.Close()
        with
        | :? InvalidOperationException as ioe -> ()

btnRemoveAttribute.Click.Add btnRemoveAttributeClick

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

Removing an Attribute Based on its Name

Another technique you can use consists of defining an XmlAttribute object and submitting to its XmlElement parent to delete. To do this, you can call the RemoveAttributeNode() method of the XmlElement object. Its signature is:

abstract RemoveAttributeNode :
        oldAttr : XmlAttribute -> XmlAttribute
override RemoveAttributeNode : 
        oldAttr : XmlAttribute -> XmlAttribute

When calling this method, pass the attribute object as argument. If the attribute exists, it would be removed and the method would return the deleted attribute. If the attribute doesn't exist, nothing would happen. Here is an example:

An alternative is to explicitly identify the attribute you want to delete. To do this, you can call the XmlAttributeCollection.Remove() method. Its signature is:

member Remove :
        node : XmlAttribute -> XmlAttribute

This method takes as attribute the XmlAttribute identification of the attribute you want to remove.

Clearing an Element of Attributes

To delete all attributes of an element, you can call the XmlAttributeCollection.RemoveAll() method. Its signature is:

member RemoveAll : unit -> unit

This method would simply remove all attributes that belong to an XmlElement object. 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 = "Time Zones",
                        ClientSize = new System.Drawing.Size(225, 120),
                        StartPosition = FormStartPosition.CenterScreen)

let btnRemoveAllAttribute = new Button(Text = "Remove All Attribute",
                                  Location = new Point(12, 12), Width = 120)
exercise.Controls.Add btnRemoveAllAttribute

let btnRemoveAllAttributeClick e =
    let strFileName = "..\..\TimeZones.xml"
    let xdTimeZones : XmlDocument = new XmlDocument()

    if File.Exists strFileName then
        use fsTimeZones = new FileStream(strFileName, FileMode.Open, FileAccess.Read)
        xdTimeZones.Load fsTimeZones
        fsTimeZones.Close()
        
        // Get a list of elements whose names are "name"
        let xnlTimeZones : XmlNodeList = xdTimeZones.GetElementsByTagName "name"
        
        // Visit each time zone element
        for xnTimeZone in xnlTimeZones do
            // Look for a time zone named Eastern Standard Time
            if xnTimeZone.InnerText = "Eastern Standard Time" then
                // Get a list of the third siblings of that node. This represents the states
                let xnlStates : XmlNodeList = xnTimeZone.NextSibling.NextSibling.ChildNodes

                // Visit each state
                for xnState in xnlStates do
                    // Look for a state named Florida
                    if xnState.InnerText = "Florida" then
                        xnState.Attributes.RemoveAll()
                        
                        use fsTimeZones = new FileStream(strFileName, FileMode.Create, FileAccess.Write)
                        xdTimeZones.Save fsTimeZones
                        fsTimeZones.Close()

btnRemoveAllAttribute.Click.Add btnRemoveAllAttributeClick

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

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<time-zones>
  <zone>
    <name initials="CST">Central Standard Time</name>
    <utc>-06:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="West South Central" bea-region="Southeast">Arkansas</state>
      <state inclusion="Split" cb-region="South Atlantic" bea-region="Southeast">Florida</state>
      <state inclusion="Entirely" cb-region="West North Central" bea-region="Plains">Minnesota</state>
      <state inclusion="Entirely" cb-region="East North Central" bea-region="Great Lakes">Ohio</state>
    </states-and-territories>
  </zone>
  <zone>
    <name initials="EST">Eastern Standard Time</name>
    <utc>-05:00</utc>
    <states-and-territories>
      <state inclusion="Split" cb-region="East South Central" bea-region="Southeast">Alabama</state>
      <state inclusion="Entirely" cb-region="New England">Maine</state>
      <state inclusion="Entirely" cb-region="New England" bea-region="New England">Vermont</state>
      <state>Florida</state>
    </states-and-territories>
  </zone>
</time-zones>

Home Copyright © 2009-2015 FunctionX Home