Home

Characteristics of XML Nodes

 

The Structure of an XML Node

 

Introduction

A seen in the previous lessons, XML is used to describe data using objects called nodes that are arranged as an upside-down tree with a root element, optional branches, and optional leaves. Consider the following example:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
    <Title>The Distinguished Gentleman</Title>
    <Director>Jonathan Lynn</Director>
    <Length>112 Minutes</Length>
    <Format>DVD</Format>
    <Rating>R</Rating>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

The nodes of an XML file in the .NET Framework are supported through the XmlNode class.

Practical LearningPractical Learning: Introducing XML Nodes

  1. Start SharpDevelop
  2. To create a new application, on the opening page, click New Combine
  3. In the New Project dialog box, make sure C# is selected in the Categories list.
    In the Templates section, click Windows Application
  4. Set the Name to CPAP3
     
  5. Click Create
  6. To create a new XML file, on the main menu, click File -> New -> File...
  7. In the Categories list of the New File dialog box, click Misc
  8. In the Templates list, click Empty XML File and click Create
  9. To save the file, on the main menu, click File -> Save
  10. Display the folder that contains the current project (CPAP3). Double-click its bin followed by its Debug sub-folders
  11. Make sure the Save As Type combo box displays Xml Files (*.xml).
    Set the File Name to Cars.xml and click Save
  12. Complete the file as follows:
    <?xml version="1.0" encoding="utf-8" ?>
    <Cars>
    	<Make MakeName="Acura">
    		<Model>Integra GS 1.8L L4</Model>
    		<Model>MDX 3.5L V6</Model>
    		<Model>NSX 3.0L V6</Model>
    		<Model>NSX 3.2L V6</Model>
    		<Model>TL 3.2L V6</Model>
    	</Make>
    	<Make MakeName="Audi">
    		<Model>A4 Quattro 1.8L Turbo</Model>
    		<Model>A4 Quattro 3.0L V6</Model>
    		<Model>S4 2.7L V6</Model>
    	</Make>
    	<Make MakeName="BMW">
    		<Model>325I 2.5L L6</Model>
    		<Model>325XI 2.5L L6</Model>
    		<Model>745I 4.4L V8</Model>
    		<Model>Z3 Coupe 3.0L L6</Model>
    	</Make>
    </Cars>
  13. Add another Empty XML file to the current project and save it as PartCategories.xml in the bin\Debug sub-folder of the current project
  14. Complete it with a few parts as follows:
    <?xml version="1.0" encoding="utf-8" ?>
    <PartCategories>
    	<PartCategory>Accessories-Exterior</PartCategory>
    	<PartCategory>Belt Drive System</PartCategory>
    	<PartCategory>Body-Exterior</PartCategory>
    	<PartCategory>Body-Interior</PartCategory>
    	<PartCategory>Brake System</PartCategory>
    	<PartCategory>Clutch</PartCategory>
    	<PartCategory>Cooling System</PartCategory>
    	<PartCategory>Drivetrain</PartCategory>
    	<PartCategory>Electrical</PartCategory>
      	<PartCategory>Miscellaneous</PartCategory>
    </PartCategories>
  15. Add another Empty XML file to the current project and save it as Parts.xml in the bin\Debug sub-folder of the current project
  16. Fill it up with a few parts as follows:
    <?xml version="1.0" encoding="utf-8" ?>
    <Parts>
    	<Part>
    		<PartNumber>293749</PartNumber>
    		<CarYear>2005</CarYear>
    		<Make>Acura</Make>
    		<Model>NSX 3.0L V6</Model>
    		<PartName Category="Engine">Oil Filter</PartName>
    		<UnitPrice>8.85</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>283759</PartNumber>
    		<CarYear>2002</CarYear>
    		<Make>Audi</Make>
    		<Model>A4 Quattro 1.8L Turbo</Model>
    		<PartName Category="Clutch">Clutch Release Bearing</PartName>
    		<UnitPrice>55.50</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>368374</PartNumber>
    		<CarYear>2002</CarYear>
    		<Make>Audi</Make>
    		<Model>A4 Quattro 1.8L Turbo</Model>
    		<PartName Category="Electrical">Alternator</PartName>
    		<UnitPrice>305.50</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>485704</PartNumber>
    		<CarYear>2002</CarYear>
    		<Make>Audi</Make>
    		<Model>A4 Quattro 1.8L Turbo</Model>
    		<PartName Category="Engine">Oil Filter</PartName>
    		<UnitPrice>5.50</UnitPrice>
    	</Part>
    	<Part>
    		<PartNumber>491759</PartNumber>
    		<CarYear>1998</CarYear>
    		<Make>BMW</Make>
    		<Model>325I 2.5L L6</Model>
    		<PartName Category="Ignition">Ignition Coil</PartName>
    		<UnitPrice>60.85</UnitPrice>
    	</Part>
    </Parts>
  17. Save all

The Types of Nodes

Because an XML file can have different kinds of nodes, to be able to identify them, each node is recognized by its specific type. The types of node of an XML file are stored in the XmlNodeType enumerator. We will review them as we move on.

 

Practical LearningPractical Learning: Introducing Node Types

  1. To add a new form, in the Projects window, right-click CPAP3 -> Add -> New File...
  2. In the Categories list, click C#
  3. In the Templates list
  4. Set the Name to NewMake.cs
     
  5. Click Create
  6. Click the Design tab and design the form as follows:
     
    Control Name Text Other Properties
    Label   New Car Make:  
    TextBox txtNewMake   Modifiers: Public
    Button btnOK OK DialogResult: OK
    Button btnCancel Cancel DialogResult: Cancel
    Form NewMake New Make AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  7. Add another form to the current project and name it NewModel.cs
  8. Design the form as follows:
     
    New Model
    Control Name Text Other Properties
    Label   Make:  
    ComboBox cboMakes   DropDownStyle: DropDownList
    Button btnNewMake New Make  
    Label   Model:  
    TextBox txtNewModel    
    Button btnOK OK DialogResult: OK
    Button btnCancel Cancel DialogResult: Cancel
    Form NewModel   AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  9. Double-click the New Make button and implement its Click event as follows:
    void BtnNewMakeClick(object sender, System.EventArgs e)
    {
    	NewMake frmNewMake = new NewMake();
    	frmNewMake.ShowDialog();
    }
  10. In the top section of the file, under the other using lines, add using System.Xml;
    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 4/9/2005
     * Time: 7:20 AM
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Xml;
  11. Add another form to the current project and name it NewCategory.cs
  12. Design the form as follows:
     
    Collge Park Auto-Parts: New Part Category - Form Design
    Control Name Text Other Properties
    Label   New Category:  
    TextBox txtNewCategory   Modifiers: Public
    Button btnOK OK DialogResult: OK
    Button btnCancel Cancel DialogResult: Cancel
    Form NewCategory New Make AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  13. Add another form to the current project and name it NewPart.cs
  14. Design the form as follows:
     
    New Part
    Control Name Text Other Properties
    Label   Year:  
    ComboBox cboYears   DropDownStyle: DropDownList
    Modifiers: Public
    Label   Make:  
    ComboBox cboMakes   DropDownStyle: DropDownList
    Modifiers: Public
    Button btnNewMake New Make  
    Label   Model:  
    ComboBox cboModels   DropDownStyle: DropDownList
    Modifiers: Public
    Button btnNewModel New Model  
    Label   Part Category:  
    ComboBox cboPartCategories   DropDownStyle: DropDownList
    Modifiers: Public
    Button btnNewCategory New Category  
    Label   Part Name:  
    TextBox txtPartName   Modifiers: Public
    Label   Unit Price:  
    TextBox txtUnitPrice 0.00 Modifiers: Public
    TextAlign: Right
    Label   Part #:  
    TextBox txtPartNumber 000000 Modifiers: Public
    TextAlign: Right
    Button btnAddPart Add Part  
    Button btnClose Close  
    Form     AcceptButton: btnAdd
    CancelButton: btnClose
    MaximizeBox: False
    StartPosition: CenterScreen
  15. Double-click an unoccupied area of the form to access its Load event and implement its as follows:
    void NewPartLoad(object sender, System.EventArgs e)
    {
    	// Fill the Year combo box with years from 1960 to the coming year
    	for(int i = DateTime.Now.Year+1; i >= 1960; i--)
    		this.cboYears.Items.Add(i.ToString());
    
    	// We will generate a random number for the item
    	// To start, we will use the miliseconds as a seed
    	DateTime tmeNow = DateTime.Now;
    	int ms = tmeNow.Millisecond;
    
    	// Now we can generate a random number between 100000 and 999999
    	Random rndNumber = new Random(ms);
    
    	// Generate three randomg characters
    	Char firstCharacter  = (Char)(rndNumber.Next(65, 90));
    		Char secondCharacter = (Char)(rndNumber.Next(65, 90));
    	Char thirdCharacter  = (Char)(rndNumber.Next(65, 90));
    	// Generate a random number made of 4 digits
    	int numberPart = rndNumber.Next(1000, 9999);
    	 
    	// Exclude the digits 1 and 0 because they create confusion
    	if( firstCharacter == 'I' || firstCharacter == 'O' )
    		firstCharacter = 'A';
    	if( secondCharacter == 'I' || secondCharacter == 'O' )
    		secondCharacter = 'A';
    	if( thirdCharacter == 'I' || thirdCharacter == 'O' )
    		thirdCharacter = 'A';
    	// Generate a random number between 1 and 3
    	int rndCombination = rndNumber.Next(1, 4);
    	string strPartNumber = null;
    
    	// Create a part number using some algorithm
    	if( rndCombination == 1 )
    		strPartNumber = firstCharacter.ToString() + secondCharacter.ToString() +
    			numberPart.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 2 )
    		strPartNumber = firstCharacter.ToString() + numberPart.ToString() +
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 3 )
    		strPartNumber = numberPart.ToString() + firstCharacter.ToString() +
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else
    		strPartNumber = rndNumber.Next(100000, 999999).ToString();
    
    	// Display the new number in the Part # text box
    	this.txtPartNumber.Text = strPartNumber;
    
    	// Disable the OK button to indicate that the part is not ready
    	this.btnAddPart.Enabled = false;
    }
  16. Click the Design tab to access the New Part form. Double-click the New Make button and implement its event as follows:
    void BtnNewMakeClick(object sender, System.EventArgs e)
    {
    	NewMake frmMake = new NewMake();
    	frmMake.ShowDialog();
    }
  17. Click the Design tab to access the New Part form. Double-click the New Model button and implement its event as follows:
    void BtnNewModelClick(object sender, System.EventArgs e)
    {
    	NewModel frmModel = new NewModel();
    	frmModel.ShowDialog();
    }
  18. Click the Design tab to access the New Part form and double-click the New Category button and implement its event as follows:
    void BtnNewCategoryClick(object sender, System.EventArgs e)
    {
    	NewCategory frmCat = new NewCategory();
    	frmCat.ShowDialog();
    }
  19. Click the Design tab to access the New Part form and double-click the Close button and implement its event as follows:
    void BtnCloseClick(object sender, System.EventArgs e)
    {
    	Close();
    }
  20. In the top section of the file, under the other using lines, add using System.Xml;
    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 4/9/2005
     * Time: 9:04 AM
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Xml;
  21. Add another form to the current project and name it OrderProcessing.cs
  22. Design the form as follows:
     
    College Park Auto Parts - Order Processing - Form Design
    Control Name Text Other Properties
    GroupBox   Part Selection  
    Label   Year:  
    Label      
    ComboBox cboYears   DropDownStyle: DropDownList
    Label   Make:  
    ComboBox cboModels   DropDownStyle: DropDownList
    Label   Model:  
    ComboBox cboMakes   DropDownStyle: DropDownList
    Label   Category:  
    ComboBox cboCategories   DropDownStyle: DropDownList
    Label   Available Parts  
    ListView lvwAvailableParts   FullRowSelect: True
    GridLines: True
    View: Details
    Columns:
    Text TextAlign Width
    Part # Center 60
    Part Name Left 220
    Unit Price Right 60
    GroupBox   Setup  
    Button btnNewPart New Part  
    Button btnClose Close  
    GroupBox   Customer Order  
    Label   Part #  
    Label   Part Name  
    Label   Unit Price  
    Label   Qty  
    Label   Sub Total  
    Label   Keep Remove  
    TextBox txtPartNumber1    
    TextBox txtPartName1    
    TextBox txtUnitPrice1 0.00 TextAlign: Right
    TextBox txtQuantity1 0 TextAlign: Right
    TextBox txtSubTotal1 0.00 TextAlign: Right
    CheckBox chkKeepRemove1    
    TextBox txtPartNumber2    
    TextBox txtPartName2    
    TextBox txtUnitPrice2 0.00 TextAlign: Right
    TextBox txtQuantity2 0 TextAlign: Right
    TextBox txtSubTotal2 0.00 TextAlign: Right
    CheckBox chkKeepRemove2    
    TextBox txtPartNumber3    
    TextBox txtPartName3    
    TextBox txtUnitPrice3 0.00 TextAlign: Right
    TextBox txtQuantity3 0 TextAlign: Right
    TextBox txtSubTotal3 0.00 TextAlign: Right
    CheckBox chkKeepRemove3    
    TextBox txtPartNumber4    
    TextBox txtPartName4    
    TextBox txtUnitPrice4 0.00 TextAlign: Right
    TextBox txtQuantity4 0 TextAlign: Right
    TextBox txtSubTotal4 0.00 TextAlign: Right
    CheckBox chkKeepRemove4    
    TextBox txtPartNumber5    
    TextBox txtPartName5    
    TextBox txtUnitPrice5 0.00 TextAlign: Right
    TextBox txtQuantity5 0 TextAlign: Right
    TextBox txtSubTotal5 0.00 TextAlign: Right
    CheckBox chkKeepRemove5    
    TextBox txtPartNumber6    
    TextBox txtPartName6    
    TextBox txtUnitPrice6 0.00 TextAlign: Right
    TextBox txtQuantity6 0 TextAlign: Right
    TextBox txtSubTotal6 0.00 TextAlign: Right
    CheckBox chkKeepRemove6    
    Label   Order saved in  
    DateTimePicker dtpFilename   Format: Custom
    CustomFormat: ddMMMyyyy
    Button btnSave Save  
    Label   Total Order:  
    TextBox txtTotalOrder 0.00 TextAlign: Right
  23. Double an unoccupied area of the form outside of any group box to generate the form's Load event
  24. Implement the Load event as follows:
    private void OrderProcessingLoad(object sender, System.EventArgs e)
    {
    	// Fill the Year combo box with years from 1960 to the coming year
    	for(int i = DateTime.Now.Year+1; i >= 1960; i--)
    		this.cboYears.Items.Add(i.ToString());
    }
  25. In the top section of the file, under the other using lines, type:
    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 4/9/2005
     * Time: 9:04 AM
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.IO;
    using System.Xml;
  26. Return to the form and double-click the New Part button
  27. Implement its Click event as follows:
    private void BtnNewPartClick(object sender, System.EventArgs e)
    {
    	NewPart frmPart = new NewPart();
    
    	frmPart.ShowDialog();
    }
  28. Return to the form. Double-click the Close button and implement its Click event as follows:
    private void BtnCloseClick(object sender, System.EventArgs e)
    {
    	Close();
    }
  29. Display the first or main form (Form1.cs [Design]) and design it as follows 
     
    Collge Park Auto-Parts: Switchboard Form Design
    Control Name Text
    Button btnOrderProcessing Order Processing
    Button btnNewPart New Part
    Button btnClose Close
  30. Double-click the Order Processing button
  31. Return to the form and double-click the New Part button
  32. Return to the form and double-click the Close button
  33. Implement the Click events as follows:
    private void BtnOrderProcessingClick(object sender, System.EventArgs e)
    {
    	OrderProcessing frmOrder = new OrderProcessing();
    
    	frmOrder.ShowDialog();
    }
    
    private void BtnNewPartClick(object sender, System.EventArgs e)
    {
    	NewPart frmPart = new NewPart();
    
    	frmPart.ShowDialog();
    }
    
    private void BtnCloseClick(object sender, System.EventArgs e)
    {
    	Close();
    }
  34. Execute the application to test it

The Children of a Node

 

Introduction

In our introduction to XML, we saw that a node can be nested inside of another. When a node is nested, the nested node is called a child of the nesting node, which is a parent node. This also implies that a node can have as many children as necessary. The child nodes of a particular node are accessed through the ChildNodes property of the XmlNode class. This property is defined as follows:

public virtual XmlNodeList ChildNodes{get};

When this property is used, it produces an XmlNodeList list, which is a collection of all nodes that share the same parent. The combined text of the values of the children of a node is available through its XmlNode.InnerText property which is declared as follows:

public virtual string InnerText{get; set};

This property concatenates the values of the children of the node that called them and doesn't include their markups. If you want to get a node, its markup, its child(ren) and its(their) markup(s), you can access its XmlNode.OuterXml property which is declared as follows:

public virtual string OuterXml{get};

If you want only the markup(s) of the child(ren) excluding the parent, access its XmlNode.InnerXml property which is declared as follows:

public virtual string InnerXml{get};
 

Practical LearningPractical Learning: Accessing Child Nodes

  1. Display the New Model form and double-click an unoccupied area of the form to access its Load event
  2. Implement the Load event as follows:
    private void NewModelLoad(object sender, System.EventArgs e)
    {
    	// We will need a reference to the XML document
    	XmlDocument docXML = new XmlDocument();
    
    	// We will start with the Make combo box
    	// Open the Cars.xml file
    	docXML.Load("Cars.xml");
    	// Get a reference to the root node
    	XmlElement nodRoot = docXML.DocumentElement;
    	// Locate all nodes whose name is Make
    	XmlNodeList nodItems = nodRoot.GetElementsByTagName("Make");
    	// Retrieve the value of each Make node and put 
    	// that value in the Make combo box
    	for(int i = 0; i < nodItems.Count; i++)
    		this.cboMakes.Items.Add(nodItems[i].Attributes["MakeName"].InnerText);
    }
  3. Access the New Part form and change its Load event as follows:
    private void NewPartLoad(object sender, System.EventArgs e)
    {
    	// Fill the Year combo box with years from 1960 to the coming year
    	for(int i = DateTime.Now.Year+1; i >= 1960; i--)
    		this.cboYears.Items.Add(i.ToString());
    
    	// We will need a reference to the XML document
    	XmlDocument docXML = new XmlDocument();
    
    	// Open the Cars.xml file
    	docXML.Load("Cars.xml");
    
    	// Get a reference to the root node
    	XmlElement nodRoot = docXML.DocumentElement;
    	// Locate all nodes whose name is Make
    	XmlNodeList nodItems = nodRoot.GetElementsByTagName("Make");
    	// Retrieve the value of each Make node and put 
    	// that value in the Make combo box
    	for(int i = 0; i < nodItems.Count; i++)
    		this.cboMakes.Items.Add(nodItems[i].Attributes["MakeName"].InnerText);
    
    	// Open the Makes.xml file
    	docXML.Load("PartCategories.xml");
    
    	// Get a reference to the root node
    	nodRoot = docXML.DocumentElement;
    	// Locate all nodes whose name is Make
    	nodItems = nodRoot.GetElementsByTagName("PartCategory");
    	// Retrieve the value of each Make node and put 
    	// that value in the Make combo box
    	for(int i = 0; i < nodItems.Count; i++)
    		this.cboPartCategories.Items.Add(nodItems[i].InnerText);
    
    	this.cboPartCategories.Text = "Miscellaneous";
    
    	// We will generate a random number for the item
    	// To start, we will use the miliseconds as a seed
    	DateTime tmeNow = DateTime.Now;
    	int ms = tmeNow.Millisecond;
    
    	// Now we can generate a random number between 100000 and 999999
    	Random rndNumber = new Random(ms);
    
    	// Generate three randomg characters
    	Char firstCharacter  = (Char)(rndNumber.Next(65, 90));
    	Char secondCharacter = (Char)(rndNumber.Next(65, 90));
    	Char thirdCharacter  = (Char)(rndNumber.Next(65, 90));
    	// Generate a random number made of 4 digits
    	int numberPart = rndNumber.Next(1000, 9999);
    	 
    	// Exclude the digits 1 and 0 because they create confusion
    	if( firstCharacter == 'I' || firstCharacter == 'O' )
    		firstCharacter = 'A';
    	if( secondCharacter == 'I' || secondCharacter == 'O' )
    		secondCharacter = 'A';
    	if( thirdCharacter == 'I' || thirdCharacter == 'O' )
    		thirdCharacter = 'A';
    	// Generate a random number between 1 and 3
    	int rndCombination = rndNumber.Next(1, 4);
    	string strPartNumber = null;
    
    	// Create a part number using some algorithm
    	if( rndCombination == 1 )
    		strPartNumber = firstCharacter.ToString() + secondCharacter.ToString() +
    			numberPart.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 2 )
    		strPartNumber = firstCharacter.ToString() + numberPart.ToString() +
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 3 )
    		strPartNumber = numberPart.ToString() + firstCharacter.ToString() +
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else
    		strPartNumber = rndNumber.Next(100000, 999999).ToString();
    
    	// Display the new number in the Part # text box
    	this.txtPartNumber.Text = strPartNumber;
    
    	// Disable the OK button to indicate that the part is not ready
    	this.btnAddPart.Enabled = false;
    }
  4. Execute the application to test it and make sure that the top combo boxes of the New Part and the New Model forms are rightly filled
  5. Close the form and return to your programming environment

The Parent of a Node

Not all nodes have children, obviously. For example, the Title node in the above example doesn't have children. To find out whether a node has children, check its HasChildNodes Boolean property that is declared as follows:

public virtual bool HasChildNodes{get};

If a node is a child, to get its parent, you can access its ParentNode property.

The First Child Node

The children of a nesting node are also recognized by their sequence. Based on this, the first node that immediately follows the start-tag of the parent node is called the first child. In the case of the above file, the first <Video> node under <Videos> is the first child of the Video node. In the .NET Framework, the first child of a node can be retrieved by accessing the XmlNode.FirstNode property declared as follows:

public virtual XmlNode FirstChild{get};

The Last Child Node

As opposed to the first child, the child node that immediately precedes the end-tag of the parent node is called the last child. To get the last child of a node, you can access its XmlNode.LastChild property that is declared as follows:

public virtual XmlNode LastChild{get};

The Siblings of a Node

The child nodes that are nested in a parent node and share the same level are referred to as siblings. Consider the following listing:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
	<Title>The Distinguished Gentleman</Title>
	<Director>Jonathan Lynn</Director>
	<Actors>
		<Actor>Eddie Murphy</Actor>
		<Actor>Lane Smith</Actor>
		<Actor>Sheryl Lee Ralph</Actor>
		<Actor>Joe Don Baker</Actor>
	</Actors>
	<Length>112 Minutes</Length>
	<Format>DVD</Format>
	<Rating>R</Rating>
  </Video>
  <Video>
	<Title>Her Alibi</Title>
	<Director>Bruce Beresford</Director>
	<Length>94 Mins</Length>
	<Format>DVD</Format>
	<Rating>PG-13</Rating>
  </Video>
</Videos>

In this example, Director, Actors, and Length are child nodes of the Video node but the Actor node is not a child of the Video node. Consequently, Director, Actors, and Length are siblings.

Obviously, to get a sibling, you must first have a node. Based on this, to access the sibling of a node, you can use its XmlNode.NextSibling property, which is declared as follows:

public virtual XmlNode NextSibling{get};

Overview of Types of Nodes

 

Introduction

To differentiate the various nodes that belong to an XML file, they are classified by their category. As mentioned earlier, the types of node are listed in the XmlNodeType enumerator.

Comments

A comment is a character, a line or a paragraph that is not considered as part of the XML code that needs to be processed. A comment allows you to insert notes or personal observations inside an XML file. For this reason, a commented section can be written any way you like. This means that a comment can include plain text, formulas, expressions, or even XML code as long as you know that that XML code will not be validated: it will ignored by the parser.

To create a comment, you use the following formula:

<!-- Blah Blah Blah -.

Between <!-- and -., any text in that section is considered a comment and you can include anything you want. Both sections of the comment use two dashes, not more, not less. Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <Video>
	<!-- In this collection, we will keep each title "as i" -.
	<Title>The Distinguished Gentleman</Title>
	<Director>Jonathan Lynn</Director>
	<Length>112 Minutes</Length>
	<Format>DVD</Format>
	<Rating>R</Rating>
  </Video>
  <Video>
	<Title>Her Alibi</Title>
	<Director>Bruce Beresford</Director>
	<Length>94 Mins</Length>
	<Format>DVD</Format>
	<Rating>PG-13</Rating>
  </Video>
</Videos>

This would produce:

The System.Xml represents a comment through the XmlComment class. Like any other part of an XML file, a comment is represented by the XmlComment.Name property. This allows you to retrieve the name of a comment that is included in the document.

To create a comment, you can call the XmlDocument.CreateComment() method. Its syntax is:

public virtual XmlComment CreateComment(string data);

This method takes as argument the text that would go into the commented section. After calling it, if the method succeeds, which it usually does, it returns the XmlComment object that was created.

Practical Learning Practical Learning: Adding a Comment to an XML File

  1. Access the Cars.xml file. To add a comment, change it as follows:
    <?xml version="1.0" encoding="utf-8" ?> 
    <Cars>
    	<!-- Each car model is organized as follows:
    	       1. The first part identifies the make of the car.
    	           We use a MakeName attribute of the Make element
    	           to identify a make
    	       2. The second part identifies the name of the model.
    	-->
    	<Make MakeName="Acura">
    		<Model>Integra GS 1.8L L4</Model>
    		<Model>MDX 3.5L V6</Model>
    		<Model>NSX 3.0L V6</Model>
    		<Model>NSX 3.2L V6</Model>
    		<Model>TL 3.2L V6</Model>
    	</Make>
    	<Make MakeName="Audi">
    		<Model>A4 Quattro 1.8L Turbo</Model>
    		<Model>A4 Quattro 3.0L V6</Model>
    		<Model>S4 2.7L V6</Model>
    	</Make>
    	<Make MakeName="BMW">
    		<Model>325I 2.5L L6</Model>
    		<Model>325XI 2.5L L6</Model>
    		<Model>745I 4.4L V8</Model>
    		<Model>Z3 Coupe 3.0L L6</Model>
    	</Make>
    </Cars>
  2. Save the file

CDATA

Except for comments, the parser is used to "scan" the whole XML file to analyze it. Every tag is then interpreted. As we mentioned already, the value of each tag can be displayed in a browser between its opening and its closing tag, and the browser uses different font styles to make a distinction. When creating some tags and some sections of the file, you may want the parser to consider those particular tags and sections as regular text. That is, you may want the parser to treat a certain tag and its value as if it were regular text even though it is created as an XML file.

To prevent the parser from interpreting a tag regularly but to treat that tag and its value as regular text, you can create it in a CDATA section. To do this, create a section that starts with <![CDATA[, followed by anything you want, and ending with ]]>. The formula used is:

<![CDATA[ Blah Blah Blah ]]>

Between <![CDATA[ and ]]>, you can type anything, including one or more normal XML tags. Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<Videos>
  <![CDATA[<VideoCollection>Personal Collection of Movies</VideoCollection>]]>
  <Video>
    <Title>The Distinguished Gentleman</Title>
    <Director>Jonathan Lynn</Director>
    <Length>112 Minutes</Length>
    <Format>DVD</Format>
    <Rating>R</Rating>
  </Video>
  <Video>
    <Title>Her Alibi</Title>
    <Director>Bruce Beresford</Director>
    <Length>94 Mins</Length>
    <Format>DVD</Format>
    <Rating>PG-13</Rating>
  </Video>
</Videos>

The .NET Framework supports the creation of a CDATA section through the XmlCDataSection class. This class is equipped with a Name property that allows you t retrieve the name of a CDATA section in an XmlDocument object.

To programmatically create a CDATA section, you can call the XmlDocument.CreateCDataSection() method. Its syntax is:

public virtual XmlCDataSection CreateCDataSection(string data);

This method receives the content of the CDATA section as argument. If the method succeeds, which it usually does, it returns an XmlCDataSection value. 

Operations on Nodes

 

Simple Node Addition

To add a new node to an XML file, the XmlNode class provides various methods. To start, an XML file must have a root. This ensures that the file has at least one node. Before adding a new node, you must have a reference of another node. This information will allow you to decide where to position the new node.

To add a new node as a child of an existing node, the simplest position to use is to add the new node at the end of the list of nodes of the existing node. This position is supported by the XmlNode.AppendChild() method. Its syntax is:

public virtual XmlNode AppendChild(XmlNode newChild);

This method accepts as argument the new node that will be created. This means that you can first "build" an XmlNode object. To do this, you can use a pointer to the type of node you want to create.

 

Practical Learning Practical Learning: Creating the Inventory

  1. Display the New Model form and double-click the New Make button
  2. Change the Click event of the btnNewMake button as follows:
    private void BtnNewMakeClick(object sender, System.EventArgs e)
    {
    	// The new car make will come from the New Make dialog box
    	 NewMake frmMake = new NewMake();
    
    	 // Display the New Make dialog box and find out if the user clicked OK
    	 if( frmMake.ShowDialog() == DialogResult.OK )
    	 {
    		 string strNewMake = frmMake.txtNewMake.Text;
    
    		 // If the user didn't create a new Make, don't do anything
    		 if( strNewMake == "" )
    			 return;
    
    		 // Before adding the new make, check that it doesn't exist already
    		 if( this.cboMakes.FindStringExact(strNewMake) > 0 )
    			 return;
    
    		 // Now you can add it
    		 this.cboMakes.Items.Add(strNewMake);
    		 // The user likely wants this new item selected
    		 this.cboMakes.Text = strNewMake;
    
    		 // Open the Cars.xml file
    		 XmlDocument docXMLFile = new XmlDocument();
    		 docXMLFile.Load("Cars.xml");
    
    		 // Get the root node so we can explore its children
    		 XmlNode nodRoot = docXMLFile.DocumentElement;
    		 
    		 // If the car is not in the list already, create its Make node
    		 XmlNode nodNewMake  = docXMLFile.CreateNode(XmlNodeType.Element, "Make", "");
    		 // Create an attribute for the node
    		 ((XmlElement)(nodNewMake)).SetAttribute("MakeName", strNewMake);
    		 
    		 // Add the new node to the XML file
    		 docXMLFile.DocumentElement.AppendChild(nodNewMake);
    		 
    		 // Save the file
    		 docXMLFile.Save("Cars.xml");
    	}
    }
  3. Display the New Part form and double-click the New Make button
  4. Change the Click event of the btnNewMake button as follows:
    private void BtnNewMakeClick(object sender, System.EventArgs e)
    {
    	// The new car make will come from the New Make dialog box
    	 NewMake frmMake = new NewMake();
    
    	 // Display the New Make dialog box and find out if the user clicked OK
    	 if( frmMake.ShowDialog() == DialogResult.OK )
    	 {
    		 string strNewMake = frmMake.txtNewMake.Text;
    
    		 // If the user didn't create a new Make, don't do anything
    		 if( strNewMake == "" )
    			 return;
    
    		 // Before adding the new make, check that it doesn't exist already
    		 if( this.cboMakes.FindStringExact(strNewMake) > 0 )
    			 return;
    
    		 // Now you can add it
    		 this.cboMakes.Items.Add(strNewMake);
    		 // The user likely wants this new item selected
    		 this.cboMakes.Text = strNewMake;
    
    		 // Open the Cars.xml file
    		 XmlDocument docXMLFile = new XmlDocument();
    		 docXMLFile.Load("Cars.xml");
    
    		 // Get the root node so we can explore its children
    		 XmlNode nodRoot = docXMLFile.DocumentElement;
    		 
    		 // If the car is not in the list already, create its Make node
    		 XmlNode nodNewMake  = docXMLFile.CreateNode(XmlNodeType.Element, "Make", "");
    		 // Create an attribute for the node
    		 ((XmlElement)(nodNewMake)).SetAttribute("MakeName", strNewMake);
    		 
    		 // Add the new node to the XML file
    		 docXMLFile.DocumentElement.AppendChild(nodNewMake);
    		 
    		 // Save the file
    		 docXMLFile.Save("Cars.xml");
    	}
    }
  5. Display the New Part form again and double-click the New Model button
  6. Change its Click event as follows:
    private void BtnNewModelClick(object sender, System.EventArgs e)
    {
    	// The new car model will come from the New Model dialog box
    	 NewModel frmModel = new NewModel();
    
    	 // Display the New Model dialog box and find out if the user clicked OK
    	 if( frmModel.ShowDialog() == DialogResult.OK )
    	 {
    		 // Retrieve the values that the user specified
    		 string strMake     = frmModel.cboMakes.Text;
    		 string strNewModel = frmModel.txtNewModel.Text;
    
    		 // If the new didn't select a Make, don't do anything
    		 if( strMake.Equals("") )
    			 return;
    		 // If the New Model string is empty, don't do anything
    		 if( strNewModel.Equals("") )
    			 return;
    
    		 // Open the Cars.xml file
    		 XmlDocument docXMLFile = new XmlDocument();
    		 docXMLFile.Load("Cars.xml");
    
    		 // Get the root node so we can explore its children
    		 XmlNode nodRoot = docXMLFile.DocumentElement;
    		 
    		 // Create a list of all Make nodes
    		 XmlNodeList lstMakes = docXMLFile.GetElementsByTagName("Make");
    
    		 // Visit each Make
    		 for(int i = 0; i < lstMakes.Count; i++)
    		 {
    			 // Get a reference to the current node
    			 XmlNode curMake = lstMakes[i];
    
    			 // If, or when you find the Make
    			 if( curMake.Attributes["MakeName"].InnerText.Equals(strMake) )
    			 {
    				 // Since we found the Make, find out if the model exists
    				 XmlNodeList lstCurrentModels = curMake.ChildNodes;
    
    				 // Check each model if the list already contains the model
    				 for(int j = 0; j < lstCurrentModels.Count; j++)
    				 {
    					 if( lstCurrentModels[j].InnerText.Equals(strNewModel) )
    					 {
    					MessageBox.Show("That model exists already in the database");
    						 return;
    					 }
    				 }
    
    				 // create a child node to it
    			    XmlNode nodModel = docXMLFile.CreateNode(XmlNodeType.Element, "Model", "");
    				 // Create its value using the string from the New Make dialog box
    				 nodModel.InnerText = strNewModel;
    				 // Add the new element at the end of the file
    				 curMake.AppendChild(nodModel);
    
    				 // Save the file
    				 docXMLFile.Save("Cars.xml");
    				 break;
    			 }
    		 }
    	}
    }
  7. Display the New Part form again and double-click the Make combo box
  8. Implement its SelectedIndexChanged event as follows:
    private void CboMakesSelectedIndexChanged(object sender, System.EventArgs e)
    {
    	// Empty the Models combo box
    	this.cboModels.Items.Clear();
    
    	// Find out if the user had selected a Make
    	string strSelectedMake = this.cboMakes.Text;
    	// Open the Cars.xml file
    	XmlDocument docXML = new XmlDocument();
    	docXML.Load("Cars.xml");
    
    	// Get a reference to the root node
    	XmlElement nodRoot = docXML.DocumentElement;
    	// Locate all nodes whose name is Make
    	XmlNodeList nodMakes = nodRoot.GetElementsByTagName("Make");
    	// Look for the Make that is the same the user selected
    	for(int i = 0; i < nodMakes.Count; i++)
    	{
    		// Retrieve the value of each Make node and put
    		string strMakeName = nodMakes[i].Attributes["MakeName"].InnerText;
    		// If you find it...
    		if( strMakeName.Equals(strSelectedMake) )
    		{
    			// If you find it, make a list of its models...
    			XmlNodeList nodAvailableModels = nodMakes[i].ChildNodes;
    			// ... then add each of its models to the Model combo box
    			for(int j = 0; j < nodAvailableModels.Count; j++)
    				this.cboModels.Items.Add(nodAvailableModels[j].InnerText);
    		}
    	}
    }
  9. Display the New Part form again and double-click the New Category button
  10. Change its Click event as follows:
    private void BtnNewCategoryClick(object sender, System.EventArgs e)
    {
    	// Get a reference to the New Part Category form
    	 NewPartCategory frmCategory = new NewPartCategory();
    
    	 // Display the New Part Category dialog box and find out if the user clicked OK
    	 if( frmCategory.ShowDialog() == DialogResult.OK )
    	 {
    		 string strCategory = frmCategory.txtNewCategory.Text;
    
    		 // If the user didn't create a new category, don't do anything
    		 if( strCategory.Equals("") )
    			 return;
    
    		 // Before adding the new category, check that it doesn't exist already
    		 if( this.cboPartCategories.FindStringExact(strCategory) > 0 )
    			 return;
    
    		 // Now you can add it
    		 this.cboPartCategories.Items.Add(strCategory);
    		 // The user likely wants this new item selected
    		 this.cboPartCategories.Text = strCategory;
    
    		 // Open the PartCategories.xml file
    		 XmlDocument docXMLFile = new XmlDocument();
    		 docXMLFile.Load("PartCategories.xml");
    
    		 // Get the root node so we can explore its children
    		 XmlNode nodRoot = docXMLFile.DocumentElement;
    		 
    		 // If the new part is not in the list already, create its node
    	XmlNode nodNewCategory  = docXMLFile.CreateNode(XmlNodeType.Element, "PartCategory", "");
    		 // Create text for the node
    		 nodNewCategory.InnerText = strCategory;
    		 
    		 // Add the new node to the XML file
    		 docXMLFile.DocumentElement.AppendChild(nodNewCategory);
    		 
    		 // Save the file
    		 docXMLFile.Save("PartCategories.xml");
    	}
    }
  11. Return to the New Part form and double-click the Part Name text box
  12. Implement its TextChanged event as follows:
    private void TxtPartNameTextChanged(object sender, System.EventArgs e)
    {
    	// If there is no part name, no need to add the item to the XML file
    	if( this.txtPartName.Text == "" )
    		this.btnAddPart.Enabled = false;
    	else
    		this.btnAddPart.Enabled = true;
    }
  13. Return to the New Part form and double-click the Unit Price text box
  14. Implement its TextChanged event as follows:
    private void TxtUnitPriceTextChanged(object sender, System.EventArgs e)
    {
    	// If the price is not specified, don't add the item to the XML file
    	if( this.txtUnitPrice.Text == "" )
    		this.btnAddPart.Enabled = false;
    	else
    		this.btnAddPart.Enabled = true;
    }
  15. Return to the New Part form and double-click the Part # text box
  16. Implement its TextChanged event as follows:
    private void TxtPartNumberTextChanged(object sender, System.EventArgs e)
    {
    	// Make sure that there is a Part Number for this item
    	// Otherwise, don't add the part to the XML file
    	if( this.txtPartNumber.Text == "" )
    		this.btnAddPart.Enabled = false;
    	else
    		this.btnAddPart.Enabled = true;
    }
  17. Return to the New Part form and double-click the Add Part button
  18. Implement its Click event as follows:
    private void BtnAddPartClick(object sender, System.EventArgs e)
    {
    	// Open the Parts.xml file
    	XmlDocument docXML = new XmlDocument();
    	docXML.Load("Parts.xml");
    
    	// Before adding the new part, make sure all components are ready
    	// Otherwise, don't add it
    	if( this.cboYears.SelectedIndex < 0 )
    	{
    		MessageBox.Show("You must specify the year. " +
    			"This will help to locate the part");
    		this.cboYears.Focus();
    		return;
    	}
    	if( this.cboMakes.SelectedIndex < 0 )
    	{
    		MessageBox.Show("Please select the car make for this part.");
    		this.cboMakes.Focus();
    		return;
    	}
    	if( this.cboModels.SelectedIndex < 0 )
    	{
    		MessageBox.Show("The car model is required. " +
    			"It helps to know the specific car this part is made for.");
    		this.cboModels.Focus();
    		return;
    	}
    	if( this.txtPartName.Text.Equals("") )
    	{
    		MessageBox.Show("You must specify the part name or a (very) short description.");
    		this.txtPartName.Focus();
    		return;
    	}
    	if( this.txtUnitPrice.Text.Equals("") )
    	{
    		MessageBox.Show("You must enter the price of each unit of this part.");
    		this.txtUnitPrice.Focus();
    		return;
    	}
    	if( this.txtPartNumber.Text.Equals("") )
    	{
    		MessageBox.Show("Every item of this database must have a number. " +
    			"The number is just a combination of letters and digits." +
    			"Please make up a number and enter it in the Part # box.");
    		this.txtPartNumber.Focus();
    		return;
    	}
    
    	// The part seems to be ready
    	// Get a reference to the root node
    	XmlElement nodNewPart = docXML.CreateElement("Part");
    	// Create a new part as a child of the root (this is a simple node addition
    	string strNewPart = "<PartNumber>", this.txtPartNumber.Text, "</PartNumber>" +
    				"<CarYear>", this.cboYears.Text, "</CarYear>" +
    				"<Make>", this.cboMakes.Text, "</Make>" +
    				"<Model>", this.cboModels.Text, "</Model>" +
    				"<PartName Category=\"", this.cboPartCategories.Text,"\">" +
    				this.txtPartName.Text, "</PartName>" +
    				"<UnitPrice>", this.txtUnitPrice.Text, "</UnitPrice>");
    	nodNewPart.InnerXml = strNewPart;
    	docXML.DocumentElement.AppendChild(nodNewPart);
    	docXML.Save("Parts.xml");
    
    	// Reset the form in case the user wants to add another part
    	this.cboYears.SelectedIndex = -1;
    	this.cboMakes.SelectedIndex = -1;
    	this.cboModels.SelectedIndex = -1;
    	this.cboPartCategories.Text = "Miscellaneou";
    	this.txtPartName.Text = "";
    	this.txtUnitPrice.Text = "";
    	 
    	// We will generate a random number for the item
    	// To start, we will use the miliseconds as a seed
    	DateTime tmeNow = DateTime.Now;
    	int ms = tmeNow.Millisecond;
    
    	// Now we can generate a random number between 100000 and 999999
    	Random rndNumber = new Random(ms);
    
    	// Generate three randomg characters
    	Char firstCharacter  = (Char)(rndNumber.Next(65, 90));
    	Char secondCharacter = (Char)(rndNumber.Next(65, 90));
    	Char thirdCharacter  = (Char)(rndNumber.Next(65, 90));
    	// Generate a random number made of 4 digits
    	int numberPart = rndNumber.Next(1000, 9999);
    	 
    	// Exclude the digits 1 and 0 because they create confusion
    	if( firstCharacter == 'I' || firstCharacter == 'O' )
    		firstCharacter = 'A';
    	if( secondCharacter == 'I' || secondCharacter == 'O' )
    		secondCharacter = 'A';
    	if( thirdCharacter == 'I' || thirdCharacter == 'O' )
    		thirdCharacter = 'A';
    	// Generate a random number between 1 and 3
    	int rndCombination = rndNumber.Next(1, 4);
    	string strPartNumber = null;
    
    	// Create a part number using some algorithm
    	if( rndCombination == 1 )
    		strPartNumber = firstCharacter.ToString() + secondCharacter.ToString() +
    			numberPart.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 2 )
    		strPartNumber = firstCharacter.ToString() + numberPart.ToString() + 
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else if( rndCombination == 3 )
    		strPartNumber = numberPart.ToString() + firstCharacter.ToString() +
    			secondCharacter.ToString() + thirdCharacter.ToString();
    	else
    		strPartNumber = rndNumber.Next(100000, 999999).ToString();
    
    	// Display the new number in the Part # text box
    	this.txtPartNumber.Text = strPartNumber;
    	this.cboYears.Focus();
    }
  19. Execute the application to test it
  20. Add a few parts as follows (let the computer generate part numbers):
     
    Year Make Model Part Category Part Name Unit Price
    2002 Audi A4 Quattro 1.8L Turbo Exhaust Exhaust Gasket 1.55
    2004 Dodge Neon SE 2.0L L4 Cooling System Radiator Fan Assembly 125.95
    2002 Audi A4 Quattro 1.8L Turbo Drivetrain Axle Differential Bearing - Left 10.25
    2000 Ford Escort 2.0L L4 Ignition Crankshaft Position Sensor 18.65
    2002 Chevrolet Silverado 2500 5.3L V8 Ignition Spark Plugs 1.55
    2004 Dodge Neon SE 2.0L L4 Engine Oil Pump 112.85
    2004 Dodge Neon SE 2.0L L4 Engine Exhaust Valve 5.85
    1986 Acura Integra LS 1.8L L4 Electrical Alternator 110.75
    1998 Toyota Corolla 1.8L L4 Cooling System Radiator 95.95
    2002 Dodge Dakota 3.9L V6 Electrical Starter Motor 145.95
    2004 Honda Civic EX 1.7L L4 Emission Oxygen Sensor 90.55
    2002 Audi A4 Quattro 1.8L Turbo Electrical Alternator 305.50
    2002 Acura NSX 3.0L V6 Engine Oil Filter 7.05
    1998 Jeep Wrangler 2.5L L4 Transfer Case Input Shaft Seal Transfer Case 6.45
    1986 Acura Integra LS 1.8L L4 Fuel/Air Fuel Cap (Regular) 4.15
    2000 Ford Escort 2.0L L4 Brake System Right Caliper Assembly Front 32.85
    2004 Dodge Neon SE 2.0L L4 Clutch Clutch Release Bearing 25.75
    1998 BMW 325I 2.5L L6 Steering Rack and Pinion Bellow Kit 19.25
    2001 Acura Integra GS 1.8L L4 Electrical Voltage Regulator 215.75
    2001 Audi S4 2.7L V6 Engine Timing Belt 35.95
    2002 Audi A4 Quattro 1.8L Turbo Exhaust Muffler Hanger 3.35
    2002 Chevrolet Silverado 2500 5.3L V8 Cooling System Radiator w/Air Tube - w/TOC 215.75
    2002 Acura NSX 3.0L V6 Engine Oil Drain Plug 1.35
    2002 Dodge Dakota 3.9L V6 Electrical Circuit Breaker 3.25
    2004 Dodge Neon SE 2.0L L4 Brake System Brake Pad 20.55
    2004 Honda Civic EX 1.7L L4 Electrical Fusible Link 3.35
    2002 Dodge Dakota 3.9L V6 Electrical Circuit Breaker 3.45
    2004 Honda Civic EX 1.7L L4 Transmission-Manual Differential Bearing 36.75
    1998 Toyota Corolla 1.8L L4 Cooling System Thermostat Standard Temperature 9.35
    2002 Audi A4 Quattro 1.8L Turbo Electrical Cooling Fan Sensor 8.65
    2002 Acura NSX 3.0L V6 Engine Oil Pump Seal 12.55
    2004 Dodge Neon SE 2.0L L4 Brake System Master Cylinder w/o ABS w/2 Wheel 102.95
    2002 Acura NSX 3.0L V6 Engine Valve Stem Oil Seal 1.75
    2002 Dodge Dakota 3.9L V6 Electrical Fuse 0.40
    1998 Toyota Corolla 1.8L L4 Cooling System Regular Thermostat 11.15
  21. Close the forms and return to your programming environment

Node Addition to Sibling 

Instead of simply adding a new node at the end of child nodes, you can specify any other position you want. For example, you may want the new node to precede an existing child node. To support this operation, the XmlNode class provides the InsertBefore() method. Its syntax is:

public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild);

The first argument of this method is the new node that will be added. The second argument is the sibling that will succeed the the new node. If you want to new node to be positioned after an existing child node, you can call the XmlNode.InsertAfter() method. Its syntax is:

public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild);
 
 

Node Removal

If you have a node you don't want or don't need anymore in the file, you can delete it. To delete a node, the XmlNode class provides the RemoveChild() method. Its syntax is:

public virtual XmlNode RemoveChild(XmlNode oldChild);

This method takes as argument the node to delete. If the node exists, it would be deleted and the method would return it. If the node doesn't exist, nothing would happen.

To delete all child nodes of a node, you can call the XmlNode.RemoveAll() method. Its syntax is:

public virtual void RemoveAll();

When called, this method will remove all child nodes, if any, of their parent node.

 

Previous Copyright © 2005-2016, FunctionX Next