|
La collection d'attributs d'un élément |
|
|
Introduction |
|
Jusqu'ici, nous avons utilisé seulement un attribut par élément. Heureusement, vous pouvez créer autant d'attributs que vous jugez nécessaire dans un élément. Pour ce faire, dactylographiez le nom de chaque attribut, lui assigner une chaîne entre guillemet et séparer l'attribut prochain avec un espace vide. Voici un exemple d'un élément avec différents attributs : |
<Video ISBN="0-7888-1623-3" ScreenRatio="Standard" SoundtrackAvailable="True" /> Comme mentionné déjà et tel que vous devriez toujours vous rappeler, les attributs appartiennent à un élément. Pour les soutenir, les attributs d'un élément sont stockés dans la propriété Attributes de la classe XmlElement. La propriété XmlElement.Attributes est basée sur une classe appelée XmlAttributeCollection. La classe XmlAttributeCollection est basée sur la classe XmlNamedNodeMap. Cette classe crée une base d'accès aux attributs en utilisant leurs noms ouleur index dans la collection. Pour savoir le nombre d'attributs dans un élément, vous pouvez utiliser la propriété XmlNamedNodeMap.Count.
Pour accéder à un attribut par sa position dans la collection, vous pouvez utiliser la méthode XmlNamedNodeMap.Item (). La classe XmlAttributeCollection est équipée d'une propriété indexée par ItemOf. Cette propriété a trois versions. La première version a la syntaxe suivante : public virtual XmlAttribute this[int i] {get;}
Cette propriété vous permet d'accéder à un attribut en considérant que les attributs sont stockés dans une rangée. Le premier ou l'attribut le plus à gauche a un index 0 ; le deuxième attribut de gauche (naturellement En plus du nom de l'élément) a un index 1, et ainsi de suite. Il peut être difficile et parfois imprévisible, dans quelques scénarios, d'accéder à un attribut par son index parce que vous devez savoir exactement où chaque attribut est placé. Considérer la version suivante de notre fichier Videos.xml XML : <?xml version="1.0" encoding="utf-8" ?>
<Videos FileDesc="Personal Video Collection">
<Video ISBN="0-7888-1623-3"
ScreenRatio="Standard"
SoundtrackAvailable="True">
<Title StoryBy="Marty Kaplan and Jonathan Reynold"
Screenplay="Marty Kaplan">The Distinguished Gentleman</Title>
<Director>Jonathan Lynn</Director>
<Actors></Actors>
<Length>112 Minutes</Length>
<Format>DVD</Format>
<Rating>R</Rating>
</Video>
<Video ISBN="0-7907-3900-3">
<Title Screenplay="Charlie Peter">Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
Dans la première vidéo, le nom du scénariste est stocké à l'index 1. Dans la deuxième vidéo, le nom du scénariste est stocké à l'index 0. Dans ce cas-ci, ce peut ne pas être une bonne idée d'utiliser l'index pour localiser un attribut. Heureusement, la deuxième version de la propriété XmlAttributeCollection.ItemOf [] a la syntaxe suivante : public virtual XmlAttribute this[string name] {get;}
Avec cette version, vous pouvez explicitement indiquer le nom de l'attribut que vous voulez.
|
En utilisant son index ou son nom, après avoir accédé à un attribut, vous pouvez le manipuler comme vous voulez. Par exemple, vous pouvez le changer ou le supprimer en utilisant les mêmes techniques que nous avons vu et exécuter sur un attribut individuel. Comme mentionné déjà, les attributs sont stockés comme liste. Puisque vous avez accès complet à cette liste et les positions de ses attributs, quand vous créer ou ajouter un nouvel attribut, vous pouvez indiquer la position que le nouvel attribut devrait avoir dans la collection. Pour créer un attribut comme premier dans un élément, vous pouvez appeler la méthode XmlAttributeCollection.Prepend (). Sa syntaxe est: public virtual XmlAttribute Prepend(XmlAttribute node); Une autre technique à utiliser consiste à localiser d'abord un attribut. Une fois que vous avez un, pour créer un nouvel attribut avant lui, vous pouvez appeler la méthode XmlAttributeCollection.InsertBefore (). Sa syntaxe est: public virtual XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode); Pour ajouter un nouvel attribut après l'attribut courant, vous pouvez appeler la méthode XmlAttributeCollection.InsertAfter (). Sa syntaxe est: public virtual XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode); Pour ajouter un attribut à la fin de la liste d'attributs d'un élément, vous pouvez appeler la méthode XmlAttributeCollection.Append (). Sa syntaxe est : public virtual XmlAttribute Append(XmlAttribute node); |
|
|
using System;
using System.IO;
using System.Xml;
namespace CountriesStatistics2
{
public static class Program
{
private static void ShowContinents()
{
string strFilename = "continents.xml";
XmlDocument xmlWorldStats = new XmlDocument();
FileStream fsWorldStats = null;
if (File.Exists(strFilename))
{
try
{
fsWorldStats = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read);
// Open the XML file
xmlWorldStats.Load(fsWorldStats);
}
finally
{
fsWorldStats.Close();
}
// Get a list of elements whose names are Continent
XmlNodeList lstContinents =
xmlWorldStats.GetElementsByTagName("Continent");
// Show the statistics on the continents
Console.WriteLine("\n===================================");
Console.WriteLine(" =-= Continents =-=");
Console.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["Area"].InnerText,
attr.Attributes["Population"].InnerText);
Console.WriteLine("-----------------------------------");
}
}
}
private static void CreateNewContinent()
{
string strContinent = null;
string strArea = null;
string strPopulation = null;
// Open the XML file
XmlDocument xmlDocContinents = new XmlDocument();
string strFilename = "continents.xml";
FileStream fsContinents = null;
if (File.Exists(strFilename))
{
try
{
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 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
Console.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's area from the user
Console.Write("Enter the area of the continent: ");
strArea = Console.ReadLine();
// Create the Area attribute
xmlNewContinent.SetAttribute("Area", strArea);
// Request 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 the element and its attribute to the document
xmlDocContinents.DocumentElement.AppendChild(xmlNewContinent);
// Save the XML file
xmlDocContinents.Save(strFilename);
ShowContinents();
}
public static int Main(string[] args)
{
int choice = 0;
Console.WriteLine(" =-= Main Menu =-=");
Console.WriteLine("0 - Quit");
Console.WriteLine("1 - Display Continents");
Console.WriteLine("2 - Create New Continent");
Console.Write("Your Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
ShowContinents();
break;
case 2:
CreateNewContinent();
break;
}
Console.WriteLine();
return 0;
}
}
}
|
=-= Main Menu =-= 0 - Quit 1 - Display Continents 2 - Create New Continent Your Choice? 2 =================================== =-= Continents =-= =================================== 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 continue . . . |
<?xml version="1.0" encoding="utf-8"?>
<World Area="510,072,000,000" Population="6,379,157,361">
<Continent Name="Africa"
Area="30,065,000"
Population="807,419,000">
<Country CountryName="Burundi"
Area="27,830"
Population="6,231,221"
Capital="Bujumbura"
Code="bi" />
</Continent>
<Continent Name="Europe"
Area="9,938,000"
Population="730,916,000">
<Country CountryName="Italy"
Area="301,230"
Population="58,057,477"
Capital="Rome"
Code="it" />
</Continent>
<Continent Name="North America"
Area="24490000"
Population="514600000" />
</World>
|
using System;
using System.IO;
using System.Xml;
namespace CountriesStatistics2
{
public static class Program
{
private static void ShowContinents()
{
string strFilename = "continents.xml";
XmlDocument xmlWorldStats = new XmlDocument();
FileStream fsWorldStats = null;
if (File.Exists(strFilename))
{
try
{
fsWorldStats = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read);
// Open the XML file
xmlWorldStats.Load(fsWorldStats);
}
finally
{
fsWorldStats.Close();
}
// Get a list of elements whose names are Continent
XmlNodeList lstContinents =
xmlWorldStats.GetElementsByTagName("Continent");
// Show the statistics on the continents
Console.WriteLine("\n===================================");
Console.WriteLine(" =-= Continents =-=");
Console.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["Area"].InnerText,
attr.Attributes["Population"].InnerText);
Console.WriteLine("-----------------------------------");
}
}
}
private static void CreateNewContinent()
{
string strContinent = null;
string strArea = null;
string strPopulation = null;
// Open the XML file
XmlDocument xmlDocContinents = new XmlDocument();
string strFilename = "continents.xml";
FileStream fsContinents = null;
if (File.Exists(strFilename))
{
try
{
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 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
Console.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's area from the user
Console.Write("Enter the area of the continent: ");
strArea = Console.ReadLine();
// Create the Area attribute
xmlNewContinent.SetAttribute("Area", strArea);
// Request 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 the element and its attribute to the document
xmlDocContinents.DocumentElement.AppendChild(xmlNewContinent);
// Save the XML file
xmlDocContinents.Save(strFilename);
ShowContinents();
}
private static void AddCountry()
{
string strContinent = null;
string strCountry = null;
string strArea = null;
string strPopulation = null;
string strCapital = null;
string strCode = null;
string strFilename = "continents.xml";
// Open the XML file
XmlDocument xmlDocContinents = new XmlDocument();
FileStream fsContinents = null;
if (File.Exists(strFilename))
{
try
{
fsContinents = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read);
// Open the XML file
xmlDocContinents.Load(fsContinents);
}
finally
{
fsContinents.Close();
}
}
// Display the list of continents to the user
Console.WriteLine("Here is a list of the created continents");
ShowContinents();
// Request a continent from the user
Console.Write("Enter the desired continent: ");
strContinent = Console.ReadLine();
// Get a list 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 list of the attributes of the current element
XmlAttributeCollection curAttributes = lstContinents[i].Attributes;
// Check each attribute, 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, get its XmlElement reference
XmlElement elmNewCountry = xmlDocContinents.CreateElement("Country");
// Request the name of a country from the user
Console.Write("Enter the name of the country: ");
strCountry = Console.ReadLine();
// Create the country specified by the user
elmNewCountry.SetAttribute("CountryName", strCountry);
// Request the area of the country from the user
Console.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 country from the user
Console.Write("Enter the population of the country: ");
strPopulation = Console.ReadLine();
// Create the Population attribute
elmNewCountry.SetAttribute("Population", strPopulation);
// Request the Capital of the country from the user
Console.Write("Enter the capital of the country: ");
strCapital = Console.ReadLine();
// Create the Capital attribute
elmNewCountry.SetAttribute("Capital", strCapital);
// Request the Internet Code of the country from the user
Console.Write("Enter the Internet Code of the country: ");
strCode = Console.ReadLine();
// Create the Internet Code attribute
elmNewCountry.SetAttribute("Code", strCode);
// Add the element (and its attribute) as
// a child of the current Continent
lstContinents[i].AppendChild(elmNewCountry);
// Save the XML file
xmlDocContinents.Save("Countries.xml");
break;
}
}
}
}
public static int Main(string[] args)
{
int choice = 0;
do
{
Console.WriteLine(" =-= Main Menu =-=");
Console.WriteLine("1 - Display Continents");
Console.WriteLine("2 - Create New Continent");
Console.WriteLine("3 - Create New Country");
Console.WriteLine("0 - Quit");
Console.Write("Your Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
ShowContinents();
break;
case 2:
CreateNewContinent();
break;
case 3:
AddCountry();
break;
default:
break;
}
} while ((choice == 1) ||
(choice == 2) ||
(choice == 3));
Console.WriteLine();
return 0;
}
}
}
|
=-= Main Menu =-= 1 - Display Continents 2 - Create New Continent 3 - Create New Country 0 - Quit Your Choice? 2 =================================== =-= Continents =-= =================================== Name Area Population =================================== Africa 30,065,000 807,419,000 ----------------------------------- Europe 9,938,000 730,916,000 ----------------------------------- 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 9,938,000 730,916,000 ----------------------------------- North America 24490000 514600000 ----------------------------------- Asia 43810582 3902404193 ----------------------------------- =-= Main Menu =-= 1 - Display Continents 2 - Create New Continent 3 - Create New Country 0 - Quit Your Choice? 3 Here is a list of the created continents =================================== =-= Continents =-= =================================== Name Area Population =================================== Africa 30,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 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 Internet code of the country: it =-= Main Menu =-= 1 - Display Continents 2 - Create New Continent 3 - Create New Country 0 - Quit Your Choice? 0 Press any key to continue . . . |
<?xml version="1.0" encoding="utf-8"?>
<World Area="510,072,000,000" Population="6,379,157,361">
<Continent Name="Africa"
Area="30,065,000"
Population="807,419,000">
<Country CountryName="Burundi"
Area="27,830"
Population="6,231,221"
Capital="Bujumbura" Code="bi" />
</Continent>
<Continent Name="Europe"
Area="9,938,000"
Population="730,916,000">
<Country CountryName="Italy"
Area="301,230"
Population="58,057,477"
Capital="Rome"
Code="it" />
</Continent>
<Continent Name="North America"
Area="24490000"
Population="514600000" />
<Continent Name="Asia"
Area="43810582"
Population="3902404193" />
</World>
|
|
Suppression d'attribut |
|
En utilisant la liste d'attributs d'un élément, vous pouvez supprimer un ou tout les attributs d'un élément. Puisque les attributs sont stockés dans une collection, vous pouvez localiser l'attribut peu désiré par son index et puis le supprimer. Pour ce faire, vous pouvez appeler la méthode XmlAttributeCollection.RemoveAt (). Sa syntaxe est : public virtual XmlAttribute RemoveAt(int i); Cette méthode s'attend à l'index de l'attribut qui doit être enlevé. Comme mentionné pour la propriété indexée XmlAttributeCollection.ItemOf, pour utiliser efficacement cette méthode RemoveAt (), vous devrait connaître l'index exact de l'attribut, autrement, vous pouvez accéder et donc supprimer à l'attribut faux. Une alternative est d'identifier explicitement l'attribut que vous voulez supprimer. Pour ce faire, vous pouvez appeler la méthode XmlAttributeCollection.Remove (). Sa syntaxe est : public virtual XmlAttribute Remove(XmlAttribute node); Cette méthode prend comme attribut l'identification XmlAttribute de l'attribut que vous voulez enlever. Pour supprimer tous les attributs d'un élément, vous pouvez appeler la méthode XmlAttributeCollection.RemoveAll (). Sa syntaxe est : public virtual void RemoveAll(); Cette méthode enlèverait simplement tous les attributs qui appartiennent à un objet XmlElement. |
|
|
||
| Précédent | Copyright © 2007, Yevol | Suivant |
|
|
||