Characteristics of XML Nodes |
|
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.
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 Learning: Introducing Node Types |
|
|
void BtnNewMakeClick(object sender, System.EventArgs e) { NewMake frmNewMake = new NewMake(); frmNewMake.ShowDialog(); }
/* * 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;
|
|
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; }
void BtnNewMakeClick(object sender, System.EventArgs e) { NewMake frmMake = new NewMake(); frmMake.ShowDialog(); }
void BtnNewModelClick(object sender, System.EventArgs e) { NewModel frmModel = new NewModel(); frmModel.ShowDialog(); }
void BtnNewCategoryClick(object sender, System.EventArgs e) { NewCategory frmCat = new NewCategory(); frmCat.ShowDialog(); }
void BtnCloseClick(object sender, System.EventArgs e) { Close(); }
/* * 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;
|
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()); }
/* * 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;
private void BtnNewPartClick(object sender, System.EventArgs e) { NewPart frmPart = new NewPart(); frmPart.ShowDialog(); }
private void BtnCloseClick(object sender, System.EventArgs e) { Close(); }
|
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(); }
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 Learning: Accessing Child Nodes |
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); }
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; }
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 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};
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 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};
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.
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.
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.
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: Creating the Inventory |
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"); } }
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"); } }
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; } } } }
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); } } }
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"); } }
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; }
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; }
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; }
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(); }
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 |
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 |
|