How to Read the Xml Element With an Attribute Name
The Attributes of an XML Element | |
Fundamentals of Attributes |
When studying XML elements we saw how they constituted the main objects of an XML document. We too saw that an element could be nested within of another chemical element. Instead of nesting an chemical element, you can transform the nested element into being function of the nesting element and thereby giving away its chemical element qualities. This is the ground of an attribute.
An aspect is a value that is created equally function of an chemical element, making that value dissimilar from the value of a regular element. At that place are similarities and differences betwixt an element and an aspect.
The element and the attribute have these in common:
- Both (must) have a proper name
- Each may or may not have a value
The differences betwixt an element and an attribute are:
- An attribute is considered a feature of an element. This means that an attribute belongs to an chemical element
- An chemical element can have ane or more attributes. An attribute cannot have an element
- An attribute must exist created in the showtime-tag of an element
- An element cannot be defined equally function of an attribute. That is, an attribute is subject to an element and an attribute doesn't own the attribute
Application: Introducing Attributes |
- Create a new Panel Awarding named CountriesStatistics1
- In the Solution Explorer, right-click CountriesStatistics1 -> Add -> New Item...
- In the center list, click XML File
- Set up the Proper noun to continents and click Add
- Change the file every bit follows:
<?xml version="1.0" encoding="utf-8" ?> <World> </World>
- To save the file, on the main carte du jour, click File -> Salvage continents.xml As...
- Access the master folder of the current project and, within of it, open a sub-folder of the same proper noun (yous should be in that folder already). In the sub-folder of the same proper name, open the bin sub-folder followed by the Debug sub-folder. Click Save
An aspect must be created inside the start-tag of an element. To manually create an attribute, type the left angle subclass of the chemical element, followed by the proper name of the element, an empty infinite, and the name of the attribute. The name follows the same rules we divers for names in XML.
An attribute should have a value that can be used to distinguish information technology. To specify the proper noun of an attribute, assign a value equally a string to its name. Imagine y'all have an ISBN element equally a child of a Video element as follows:
<Video> <ISBN>0-7888-1623-3</ISBN> </Video>
In this case, since ISBN is merely a child of the Video element, y'all can change the ISBN element to become an aspect of the Video element equally follows:
<Video ISBN="0-7888-1623-three">
Now, ISBN is an attribute of the Video element.
Operations on an XML Attribute |
In the .NET Framework, an attribute is represented past the XmlAttribute grade. Like all nodes, this class is based on the XmlNode class. The name of an aspect is represented by its (read-simply) Name property. The value of an aspect is represented by its Value holding . Besides Value, yous tin also apply XmlAttribute.InnerText or XmlAttribute.InnerXml to admission the text of an aspect.
Manually Creating an Aspect |
An element can accept 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 form is based on the XmlNamedNodeMap grade.
Before performing an aspect-related performance on an element, to notice out whether the element has whatsoever aspect, yous can check the value of the Boolean HasAttributes belongings of its XmlElement chemical element. If this belongings produces a true value, and so the chemical element has at least i aspect; otherwise, the element doesn't accept any.
While a certain element may have an attribute, a sibling element with the same name may not have an aspect or may have a completely different blazon of attribute. Hither is an XML file with attributes in some elements:
<?xml version="1.0" encoding="utf-8" ?> <Videos> <Video ISBN="0-7888-1623-3"> <Championship 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> <Title WrittenBy="Charlie Peter">Her Alibi</Title> <Managing director>Bruce Beresford</Manager> <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 ways that yous tin type an aspect on the next line of its element'south name. In the Lesson 36, nosotros saw that every element must exist closed. Nosotros saw that we could close an element with an end-tag every bit follows:
<Video><ISBN>0-7888-1623-3</ISBN></Video>
Nosotros also saw that we could close an element locally as follows: <Video />. If yous create an aspect in an empty chemical element, you can also close it by typing the indicative forwards slash before the right angle bracket and afterwards an empty space. Hither is an example:
<Video ISBN="0-7888-1623-three" />
Application: Creating Simple Attributes |
- Change the file continents.xml file every bit follows:
<?xml version="1.0" encoding="utf-eight" ?> <World> <Continent Name="Africa"></Continent> <Continent Name="Europe"></Continent> <Continent Name="Asia"></Continent> <Continent Name="South America"></Continent> </World>
Programmatically Creating an Attribute |
As mentioned already, an attribute primarily belongs to an element. This means that, when creating an attribute, yous must specify what element information technology would belong to. To support the attributes of an chemical element, the XmlElement grade is equipped with the SetAttribute() method which is overloaded in two versions. The kickoff version of this method uses the following syntax:
public virtual void SetAttribute(string proper name, string value);
The first argument is the proper noun of the new attribute and the 2nd argument will be its text. Before calculation an attribute, you should commencement identify its parent element. Here is an example that adds an attribute to the root element:
using Organization; using System.IO; using System.Xml; namespace VideoCollection { public static grade Exercise { private static void CreateAttribute() { string strFilename = "Videos.xml"; XmlDocument docXML = new XmlDocument(); if (File.Exists(strFilename)) { // Open the XML file docXML.Load(strFilename); // Create an attribute and add it to the root chemical element docXML.DocumentElement.SetAttribute("FileDesc", "Personal Video Drove"); docXML.Relieve("Videos.xml"); } } static int Chief(string[] args) { CreateAttribute(); return 0; } } }
From the above Videos.xml file, this code would result in:
<?xml version="i.0" encoding="utf-8"?> <Videos FileDesc="Personal Video Collection"> <Video ISBN="0-7888-1623-three"> <Championship Screenplay="Marty Kaplan">The Distinguished Admirer</Title> <Director>Jonathan Lynn</Director> <Actors> </Actors> <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-thirteen</Rating> </Video> </Videos>
To support attribute improver, the XmlDocument course is equipped with the CreateAttribute() method, which is overloaded in three versions. The starting time version of this method has the following syntax:
public XmlAttribute CreateAttribute(string proper name);
This method expects the proper name of the aspect equally argument. If it succeeds, this method produces an XmlAttribute object. To add the new attribute to an chemical element, you can phone call the XmlElement.SetAttributeNote() method. This method is overloaded in two versions. One of the versions uses the following syntax:
public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr);
This method expects an XmlAttribute object. Hither is an instance that looks for a item video in a collection and adds an ISBN attribute to information technology:
using System; using System.IO; using System.Xml; namespace VideoCollection { public static class Do { private static void CreateAttribute() { cord strFilename = "Videos.xml"; XmlDocument docXML = new XmlDocument(); if (File.Exists(strFilename)) { // Open up the XML file docXML.Load(strFilename); // Create a new attribute XmlAttribute atrXML = docXML.CreateAttribute("ISBN"); atrXML.Value = "0-7907-3900-3"; // Get a list of elements whose names are Video XmlNodeList nodVideos = docXML.GetElementsByTagName("Video"); // Since we will look for a specific video, get the list of all titles XmlNodeList nodTitles = docXML.GetElementsByTagName("Title"); // Visit each championship for (int i = 0; i < nodTitles.Count; i++) { // Look for a video whose title is "Her Alibi" if (nodTitles[i].InnerText.Equals("Her Excuse")) { // In one case y'all detect that video, add together the new aspect to it ((XmlElement)(nodVideos[i])).SetAttributeNode(atrXML); } } docXML.Relieve("Videos.xml"); } } static int Principal(string[] args) { CreateAttribute(); return 0; } } }
From the above Videos.xml file, this lawmaking would effect in:
<?xml version="1.0" encoding="utf-8"?> <Videos FileDesc="Personal Video Drove"> <Video ISBN="0-7888-1623-3"> <Title Screenplay="Marty Kaplan">The Distinguished Admirer</Championship> <Director>Jonathan Lynn</Director> <Actors> </Actors> <Length>112 Minutes</Length> <Format>DVD</Format> <Rating>R</Rating> </Video> <Video ISBN="0-7907-3900-3"> <Championship WrittenBy="Charlie Peter">Her Excuse</Championship> <Managing director>Bruce Beresford</Director> <Length>94 Mins</Length> <Format>DVD</Format> <Rating>PG-13</Rating> </Video> </Videos>
Application: Creating an Attribute |
- Access the Plan.cs file and change information technology every bit follows:
using System; using System.Collections.Generic; using Arrangement.Linq; using Arrangement.Text; using System.IO; using Arrangement.Xml; namespace CountriesStatistics1 { public form Program { private static void CreateContinent() { string strFilename = "continents.xml"; XmlDocument xmlDocContinents = new XmlDocument(); FileStream fsStatistics = zippo; if (File.Exists(strFilename)) { string strContinent = null; endeavour { fsStatistics = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlDocContinents.Load(fsStatistics); } finally { fsStatistics.Shut(); } // Request the name of a continent from the user Panel.Write("Enter the name of a continent: "); strContinent = Console.ReadLine(); // Create an chemical element that the new attribute volition exist added to XmlElement xmlNewContinent = xmlDocContinents.CreateElement("Continent"); // Create a Continent element and set its value to // that of the new continent xmlNewContinent.SetAttribute("Proper noun", strContinent); // Add the element and its attribute to the certificate xmlDocContinents.DocumentElement.AppendChild(xmlNewContinent); // Salvage the XML file xmlDocContinents.Save("continents.xml"); } } static int Primary(string[] args) { CreateContinent(); return 0; } } }
- Execute the application and create a continent. Hither is an example:
Enter the name of a continent: North America Press whatever primal to continue . . .
- Close the DOS window
<?xml version="i.0" encoding="utf-8"?> <World> <Continent Name="Africa"> </Continent> <Continent Name="Europe"> </Continent> <Continent Name="Asia"> </Continent> <Continent Name="S America"> </Continent> <Continent Proper name="North America" /> </World>
The Parent of an Attribute |
Once an attribute has been created, to identify the element it belongs to, you can admission its XmlAttribute.OwnerElement holding. This property produces an XmlElement value.
If an element has an attribute y'all don't want or that you don't need anymore, yous can delete that attribute. You have various options, two are available through the XmlElement class.
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 alphabetize i, and then on. Based on this, to remove an attribute by locating it based on its index, you tin call the XmlElement.RemoveAt() method. Its syntax is:
public virtual XmlNode RemoveAttributeAt(int i);
When calling this method, if an attribute exists at position i, it will exist deleted and the method would return information technology. If in that location is no attribute at that index, the method doesn't do anything and it returns 0.
Using the XmlElement.RemoveAt() method to delete an aspect can be uncertain because you would non know whether at that place is an attribute at the specified position. An culling is to specify the name of the attribute you want to delete. To support this, the XmlElement course is equipped with the RemoveAttribute() method, which is overloaded with two versions. 1 of the versions of this method uses the following syntax:
public virtual void RemoveAttribute(string name);
This method expects as statement the name of the attribute to remove.
Some other technique you tin use consists of defining an XmlAttribute object and submitting to its XmlElement parent to delete. To practice this, y'all can call the RemoveAttributeNode() method of the XmlElement object. Its syntax is:
public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr);
When calling this method, pass the attribute object as argument. If the aspect exists, it would be removed and the method would return the deleted aspect. If the aspect doesn't be, cypher would happen.
The Collection of Attributes of an Element |
So far, we have used only one attribute per element. Fortunately, you tin create as many attributes as you judge necessary in an element. To practise this, type the proper name of each attribute, assign it a double-quoted string and separate the attribute from the next with an empty space. Here is an example of an element with different attributes:
<Video ISBN="0-7888-1623-iii" ScreenRatio="Standard" SoundtrackAvailable="True" />
Every bit mentioned already and as you should always call up, attributes belong to an element. To back up them, the attributes of an element are stored in the Attributes property of the XmlElement form. The XmlElement.Attributes property is based on a class called XmlAttributeCollection. The XmlAttributeCollection form is based on the XmlNamedNodeMap grade. This grade lays a foundation to access attributes using their names or index in the collection.
To know the number of attributes in an chemical element, y'all can apply the XmlNamedNodeMap.Count holding.
Awarding: Calculation Attributes |
- Create a new Panel Application named CountriesStatistics2
- In the Solution Explorer, correct-click CountriesStatistics2 -> Add -> New Item...
- In the center list, make certain XML File is selected.
Set the Name to continents and click Add - Change the file as follows:
<?xml version="1.0" encoding="utf-8" ?> <World Area="510,072,000,000" Population="6,379,157,361"> <Continent Name="Africa" Surface area="xxx,065,000" Population="807,419,000"> <Country CountryName="Burundi" Area="27,830" Population="6,231,221" Capital letter="Bujumbura" Lawmaking="bi" /> </Continent> <Continent Proper noun="Europe" Area="9,938,000" Population="730,916,000"> <Country CountryName="Italian republic" Expanse="301,230" Population="58,057,477" Capital="Rome" Lawmaking="information technology" /> </Continent> </World>
- To save the file, on the main carte, click File -> Salvage continents.xml Equally...
- Admission the primary folder of the current projection and, within of it, open a sub-folder of the same proper noun (y'all should be in that folder already). In the sub-folder of the same name, open the bin sub-folder followed by the Debug sub-folder. Click Salve
To admission an aspect past its position in the drove, yous can utilize the XmlNamedNodeMap.Detail() method.
The XmlAttributeCollection form is equipped with an ItemOf indexed property. This property is overloaded in three versions. The first version has the post-obit syntax:
public virtual XmlAttribute this[int i] {go;}
This belongings allows you to admission an attribute by because that the attributes are stored in an array. The starting time or nearly 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 exist difficult and sometimes unpredictable, in some scenarios, to access an attribute by its alphabetize considering y'all must know exactly where each attribute is positioned. Consider the post-obit version of our Videos.xml XML file:
<?xml version="1.0" encoding="utf-8" ?> <Videos FileDesc="Personal Video Collection"> <Video ISBN="0-7888-1623-three" ScreenRatio="Standard" SoundtrackAvailable="Truthful"> <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"> <Championship Screenplay="Charlie Peter">Her Excuse</Title> <Managing 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 author is stored at index 1. In the second video, the proper name of the screenplay writer is stored at alphabetize 0. In this instance, information technology may non 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 syntax:
public virtual XmlAttribute this[string name] {get;}
With this version, you tin explicitly specify the name of the attribute that you want.
Application: Accessing an Attribute |
- Access the Programme.cs file
- To display the continents, change the code every bit follows:
using Organisation; using System.Collections.Generic; using System.Linq; using System.Text; using Organisation.IO; using System.Xml; namespace CountriesStatistics2 { public grade Program { private static void ShowContinents() { string strFilename = "continents.xml"; XmlDocument xmlWorldStats = new XmlDocument(); FileStream fsWorldStats = null; if (File.Exists(strFilename)) { string strContinent = null; endeavor { fsWorldStats = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlWorldStats.Load(fsWorldStats); } finally { fsWorldStats.Shut(); } // Get a listing of elements whose names are Continent XmlNodeList lstContinents = xmlWorldStats.GetElementsByTagName("Continent"); // Show the statistics on the continents Console.WriteLine(" =-= Continents =-="); Console.WriteLine("Proper name\tArea\t\tPopulation"); foreach(XmlNode attr in lstContinents) { Console.WriteLine("{0}\t{one}\t{2}", attr.Attributes["Proper noun"].InnerText, attr.Attributes["Area"].InnerText, attr.Attributes["Population"].InnerText); } } } public static int Main(string[] args) { ShowContinents(); return 0; } } }
- Execute the awarding to see the upshot:
=-= Continents =-= Name Area Population Africa xxx,065,000 807,419,000 Europe 9,938,000 730,916,000 Press any key to continue . . .
- Close the DOS window
Whether using its index or name, after accessing an aspect, you lot can manipulate it as you run across fit. For example, y'all tin can change or delete it using the aforementioned techniques we saw to perform on an individual attribute.
As mentioned already, the attributes are stored as a list. Because you accept complete access to this list and the positions of its attributes, when creating or adding a new aspect, you lot can specify the position the new attribute should have in the drove. To create an attribute as the beginning in an element, you lot can telephone call the XmlAttributeCollection.Prepend() method. Its syntax is:
public virtual XmlAttribute Prepend(XmlAttribute node);
Another technique you can use consists of locating an attribute starting time. Once you have ane, to create a new attribute before information technology, you tin call the XmlAttributeCollection.InsertBefore() method. Its syntax is:
public virtual XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode);
To add a new attribute later the current one, you tin can call the XmlAttributeCollection.InsertAfter() method. Its syntax is:
public virtual XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode);
To add together an attribute at the finish of the list of attributes of an chemical element, you can call the XmlAttributeCollection.Append() method. Its syntax is:
public virtual XmlAttribute Append(XmlAttribute node);
Application: Creating Attributes |
- To permit the user to create a new continent, modify the Program.cs file as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; namespace CountriesStatistics2 { public grade Program { private static void ShowContinents() { cord strFilename = "continents.xml"; XmlDocument xmlWorldStats = new XmlDocument(); FileStream fsWorldStats = zippo; if (File.Exists(strFilename)) { endeavor { fsWorldStats = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlWorldStats.Load(fsWorldStats); } finally { fsWorldStats.Shut(); } // Get a list of elements whose names are Continent XmlNodeList lstContinents = xmlWorldStats.GetElementsByTagName("Continent"); // Testify the statistics on the continents Panel.WriteLine("\n==================================="); Console.WriteLine(" =-= Continents =-="); Console.WriteLine("==================================="); Console.WriteLine("Name\tArea\t\tPopulation"); Console.WriteLine("==================================="); foreach (XmlNode attr in lstContinents) { Panel.WriteLine("{0}\t{1}\t{two}", attr.Attributes["Name"].InnerText, attr.Attributes["Area"].InnerText, attr.Attributes["Population"].InnerText); Console.WriteLine("-----------------------------------"); } } } private static void CreateNewContinent() { string strContinent = null; string strArea = null; cord strPopulation = zero; // Open the XML file XmlDocument xmlDocContinents = new XmlDocument(); cord strFilename = "continents.xml"; FileStream fsContinents = cipher; if (File.Exists(strFilename)) { attempt { fsContinents = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlDocContinents.Load(fsContinents); } finally { fsContinents.Close(); } } // Create a Continent chemical element that the new aspect will be added to XmlElement xmlNewContinent = xmlDocContinents.CreateElement("Continent"); // Present the current list of continents to the user ShowContinents(); // Request the name of a continent from the user Panel.Write("Enter a new continent: "); strContinent = Panel.ReadLine(); // Create a Name attribute using the continent that the user entered xmlNewContinent.SetAttribute("Proper noun", strContinent); // Request the continent's area from the user Console.Write("Enter the area of the continent: "); strArea = Console.ReadLine(); // Create the Area aspect xmlNewContinent.SetAttribute("Surface area", strArea); // Request the population of the continent from the user Panel.Write("Enter the population of the continent: "); strPopulation = Console.ReadLine(); // Create the Population attribute xmlNewContinent.SetAttribute("Population", strPopulation); // Add the element and its attribute to the document xmlDocContinents.DocumentElement.AppendChild(xmlNewContinent); // Save the XML file xmlDocContinents.Salvage(strFilename); ShowContinents(); } public static int Principal(string[] args) { int choice = 0; Console.WriteLine(" =-= Main Menu =-="); Panel.WriteLine("0 - Quit"); Console.WriteLine("i - Brandish Continents"); Console.WriteLine("2 - Create New Continent"); Console.Write("Your Choice? "); choice = int.Parse(Console.ReadLine()); switch (pick) { case 1: ShowContinents(); interruption; case 2: CreateNewContinent(); suspension; } Console.WriteLine(); render 0; } } }
- Execute the application to test it. Hither is an example:
=-= Master Menu =-= 0 - Quit one - Display Continents 2 - Create New Continent Your Choice? 2 =================================== =-= Continents =-= =================================== Proper name Area Population =================================== Africa 30,065,000 807,419,000 ----------------------------------- Europe 9,938,000 730,916,000 ----------------------------------- Enter a new continent: North America Enter the area of the continent: 24490000 Enter the population of the continent: 514600000 =================================== =-= Continents =-= =================================== Name Area Population =================================== Africa 30,065,000 807,419,000 ----------------------------------- Europe 9,938,000 730,916,000 ----------------------------------- North America 24490000 514600000 ----------------------------------- Press any key to keep . . .
- Close the DOS window
<?xml version="ane.0" encoding="utf-8"?> <Earth Area="510,072,000,000" Population="half dozen,379,157,361"> <Continent Name="Africa" Expanse="30,065,000" Population="807,419,000"> <Country CountryName="Burundi" Area="27,830" Population="six,231,221" Capital="Bujumbura" Code="bi" /> </Continent> <Continent Proper noun="Europe" Surface area="9,938,000" Population="730,916,000"> <State CountryName="Italy" Area="301,230" Population="58,057,477" Capital="Rome" Code="it" /> </Continent> <Continent Name="N America" Area="24490000" Population="514600000" /> </Earth>
- To allow the user to create a new country, change the file as follows:
using Organization; using Arrangement.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; namespace CountriesStatistics2 { public class Programme { individual static void ShowContinents() { string strFilename = "continents.xml"; XmlDocument xmlWorldStats = new XmlDocument(); FileStream fsWorldStats = null; if (File.Exists(strFilename)) { attempt { fsWorldStats = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlWorldStats.Load(fsWorldStats); } finally { fsWorldStats.Shut(); } // Become a list of elements whose names are Continent XmlNodeList lstContinents = xmlWorldStats.GetElementsByTagName("Continent"); // Show the statistics on the continents Panel.WriteLine("\n==================================="); Console.WriteLine(" =-= Continents =-="); Panel.WriteLine("==================================="); Console.WriteLine("Name\tArea\t\tPopulation"); Console.WriteLine("==================================="); foreach (XmlNode attr in lstContinents) { Console.WriteLine("{0}\t{1}\t{2}", attr.Attributes["Name"].InnerText, attr.Attributes["Expanse"].InnerText, attr.Attributes["Population"].InnerText); Console.WriteLine("-----------------------------------"); } } } private static void CreateNewContinent() { string strContinent = goose egg; string strArea = nada; string strPopulation = null; // Open the XML file XmlDocument xmlDocContinents = new XmlDocument(); string strFilename = "continents.xml"; FileStream fsContinents = null; if (File.Exists(strFilename)) { effort { fsContinents = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlDocContinents.Load(fsContinents); } finally { fsContinents.Close(); } } // Create a Continent element that the new attribute will exist added to XmlElement xmlNewContinent = xmlDocContinents.CreateElement("Continent"); // Present the current listing of continents to the user ShowContinents(); // Asking the name of a continent from the user Panel.Write("Enter a new continent: "); strContinent = Console.ReadLine(); // Create a Name attribute using the continent that the user entered xmlNewContinent.SetAttribute("Name", strContinent); // Request the continent'south area from the user Console.Write("Enter the area of the continent: "); strArea = Console.ReadLine(); // Create the Area aspect xmlNewContinent.SetAttribute("Area", strArea); // Asking the population of the continent from the user Console.Write("Enter the population of the continent: "); strPopulation = Console.ReadLine(); // Create the Population attribute xmlNewContinent.SetAttribute("Population", strPopulation); // Add together the element and its attribute to the certificate xmlDocContinents.DocumentElement.AppendChild(xmlNewContinent); // Save the XML file xmlDocContinents.Relieve(strFilename); ShowContinents(); } private static void AddCountry() { string strContinent = null; string strCountry = goose egg; string strArea = nada; string strPopulation = null; string strCapital = null; cord strCode = null; cord strFilename = "continents.xml"; // Open the XML file XmlDocument xmlDocContinents = new XmlDocument(); FileStream fsContinents = goose egg; if (File.Exists(strFilename)) { try { fsContinents = new FileStream(strFilename, FileMode.Open, FileAccess.Read); // Open the XML file xmlDocContinents.Load(fsContinents); } finally { fsContinents.Shut(); } } // Display the listing of continents to the user Console.WriteLine("Hither is a listing of the created continents"); ShowContinents(); // Request a continent from the user Panel.Write("Enter the desired continent: "); strContinent = Panel.ReadLine(); // Get a listing of elements whose names are Continent XmlNodeList lstContinents = xmlDocContinents.GetElementsByTagName("Continent"); // Visit each Continent element for (int i = 0; i < lstContinents.Count; i++) { // Get a listing of the attributes of the current element XmlAttributeCollection curAttributes = lstContinents[i].Attributes; // Check each aspect, looking for // the continent that the user entered for (int j = 0; j < curAttributes.Count; j++) { // Check if the current continent // is the same that the user selected if (curAttributes["Name"].InnerText == strContinent) { // Once you find one, go its XmlElement reference XmlElement elmNewCountry = xmlDocContinents.CreateElement("Country"); // Asking the name of a state from the user Console.Write("Enter the name of the state: "); strCountry = Console.ReadLine(); // Create the country specified past the user elmNewCountry.SetAttribute("CountryName", strCountry); // Request the area of the country from the user Panel.Write("Enter the area of the country: "); strArea = Console.ReadLine(); // Create the Area specified by the user elmNewCountry.SetAttribute("Area", strArea); // Request the population of the land from the user Console.Write("Enter the population of the land: "); strPopulation = Console.ReadLine(); // Create the Population attribute elmNewCountry.SetAttribute("Population", strPopulation); // Request the Capital of the country from the user Console.Write("Enter the uppercase of the country: "); strCapital = Panel.ReadLine(); // Create the Majuscule attribute elmNewCountry.SetAttribute("Capital", strCapital); // Request the Internet Lawmaking of the country from the user Panel.Write("Enter the Internet Code of the country: "); strCode = Console.ReadLine(); // Create the Internet Code aspect elmNewCountry.SetAttribute("Lawmaking", strCode); // Add the element (and its attribute) every bit // a child of the current Continent lstContinents[i].AppendChild(elmNewCountry); // Salve the XML file xmlDocContinents.Save("Countries.xml"); break; } } } } public static int Main(string[] args) { int pick = 0; do { Console.WriteLine(" =-= Master Menu =-="); Console.WriteLine("1 - Display Continents"); Console.WriteLine("ii - Create New Continent"); Console.WriteLine("iii - Create New Country"); Console.WriteLine("0 - Quit"); Console.Write("Your Pick? "); selection = int.Parse(Console.ReadLine()); switch (selection) { instance 1: ShowContinents(); intermission; case 2: CreateNewContinent(); break; case iii: AddCountry(); break; default: break; } } while ((pick == 1) || (choice == ii) || (choice == 3)); Panel.WriteLine(); return 0; } } }
- Execute the application to test it. Hither is an example:
=-= Main Card =-= 1 - Display Continents 2 - Create New Continent 3 - Create New State 0 - Quit Your Choice? two =================================== =-= Continents =-= =================================== Name Area Population =================================== Africa 30,065,000 807,419,000 ----------------------------------- Europe 9,938,000 730,916,000 ----------------------------------- Due north America 24490000 514600000 ----------------------------------- Enter a new continent: Asia Enter the area of the continent: 43810582 Enter the population of the continent: 3902404193 =================================== =-= Continents =-= =================================== Name Area Population =================================== Africa 30,065,000 807,419,000 ----------------------------------- Europe nine,938,000 730,916,000 ----------------------------------- North America 24490000 514600000 ----------------------------------- Asia 43810582 3902404193 ----------------------------------- =-= Chief Bill of fare =-= 1 - Display Continents ii - Create New Continent three - Create New Country 0 - Quit Your Choice? three Here is a listing of the created continents =================================== =-= Continents =-= =================================== Name Expanse Population =================================== Africa thirty,065,000 807,419,000 ----------------------------------- Europe 9,938,000 730,916,000 ----------------------------------- North America 24490000 514600000 ----------------------------------- Asia 43810582 3902404193 ----------------------------------- Enter the desired continent: Europe Enter the proper name of the country: Italy Enter the area of the country: 301230 Enter the population of the country: 58751711 Enter the capital of the country: Rome Enter the Cyberspace lawmaking of the land: information technology =-= Principal Menu =-= 1 - Display Continents 2 - Create New Continent 3 - Create New Land 0 - Quit Your Choice? 0 Press any cardinal to go on . . .
- Close the DOS window
<?xml version="1.0" encoding="utf-viii"?> <Globe Area="510,072,000,000" Population="6,379,157,361"> <Continent Proper noun="Africa" Surface area="thirty,065,000" Population="807,419,000"> <Land CountryName="Republic of burundi" Surface area="27,830" Population="6,231,221" Capital="Bujumbura" Lawmaking="bi" /> </Continent> <Continent Name="Europe" Expanse="9,938,000" Population="730,916,000"> <Land CountryName="Italy" Area="301,230" Population="58,057,477" Capital="Rome" Lawmaking="information technology" /> </Continent> <Continent Name="North America" Area="24490000" Population="514600000" /> <Continent Proper noun="Asia" Area="43810582" Population="3902404193" /> </World>
Using the list of attributes of an chemical element, y'all 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 and so delete information technology. To do this, you can call the XmlAttributeCollection.RemoveAt() method. Its syntax is:
public virtual XmlAttribute RemoveAt(int i);
This method expects the index of the attribute that needs to be removed. Equally mentioned for the XmlAttributeCollection.ItemOf indexed property, to efficiently use this RemoveAt() method, yous should know the verbal alphabetize of the attribute, otherwise, y'all may access and therefore delete the incorrect aspect. An alternative is to explicitly place the aspect you want to delete. To do this, you can call the XmlAttributeCollection.Remove() method. Its syntax is:
public virtual XmlAttribute Remove(XmlAttribute node);
This method takes equally attribute the XmlAttribute identification of the attribute you want to remove.
To delete all attributes of an element, yous can phone call the XmlAttributeCollection.RemoveAll() method. Its syntax is:
public virtual void RemoveAll();
This method would simply remove all attributes that belong to an XmlElement object.
Source: http://www.functionx.com/csharp40/xml/Lesson04.htm
0 Response to "How to Read the Xml Element With an Attribute Name"
Enregistrer un commentaire