|
Insertion d'un élément |
|
|
Plac un élément |
|
Jusqu'ici, nous avions ajouté des noeuds tout à fait aléatoirement, c'est-à-dire, sans beaucoup de précision. Dans certains cas, vous pouvez vouloir effectuer une opération sur un noeud existant et particulier. Par exemple, vous pouvez vouloir changer la valeur d'un noeud, vous pouvez vouloir ajouter un nouveau noeud enfant à un noeud existant, etc. . Avant de prendre une quelconque de ces mesures, vous devez pouvoir placer ou identifier l'élément désiré. Pour vous aider à trouver un noeud, la classe XmlDocument est équipée de la méthode GetElementByTagName () qui a deux versions. Une des syntaxes utilisées est : |
public virtual XmlNodeList GetElementsByTagName(string name); Cette méthode prend comme argument une chaîne. La chaîne doit être le nom d'un noeud. Si au moins un noeud qui contient ce nom existe dans le fichier, cette méthode renvoie une collection de noeuds avec ce nom. S'il n'y a aucun noeud avec ce nom, la collection retourné est vide et il n'y a aucune exception. Voici un exemple d'appel de la méthode : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of nodes whose name is Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// Now you can check each node of the list
foreach(XmlNode node in lstTitles)
{
;
}
}
Console.WriteLine();
return 0;
}
}
}
Une fois que vous avez une liste de noeuds à partir d'un critère particulier, vous pouvez alors agir comme vous souhaîtez. Par exemple, vous pouvez rechercher un noeud particulier qui stocke un texte de votre choix. Voici un exemple : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
//XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");
// Create a list of nodes whose name is Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// Now you can check each node of the list
foreach(XmlNode node in lstTitles)
{
if (node.InnerText == "Her Alibi")
{
;
}
}
}
Console.WriteLine();
return 0;
}
}
}
De nouveau, considérez notre fichier Videos.xml : <?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>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
Imaginez que voulez ajouter une liste d'acteurs de la vidéo Her Alibi. La première action à prendre est de localiser la vidéo, ce que vous pouvez faire en appelant la méthode XmlDocument.GetElementsByTagName () appliquée à une collection de noeuds dont les noms sont Video. De cette liste de noeuds, vous pouvez rechercher le noeud dont la valeur est « Her Alibi ». Une fois que vous avez trouvé cet élément, obtenez une référence à son parent. Ajouter alors le nouveau noeud comme objet LastChild de son parent. Ceci peut être fait comme suit: using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of nodes whose name is Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// visit each node named Title
foreach(XmlNode node in lstTitles)
{
// When you get to a node, look for the element's value
// If you find an element whose value is Her Alibi
if (node.InnerText == "Her Alibi")
{
// Create an element named Actors
XmlElement elmNew = xmlDoc.CreateElement("Actors");
XmlNode elmParent = node.ParentNode;
// Add a new element named Actors to it
elmParent.AppendChild(elmNew);
xmlDoc.Save(strFilename);
}
}
}
Console.WriteLine();
return 0;
}
}
}
Ceci produirait : <?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>
<Actors />
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
Ce code crée un élément vide. Si vous voulez créer un élément qui inclut une valeur, créer son texte et ajouter ce texte comme LastChild de son parent. Voici un exemple : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of nodes whose name is Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// visit each node named Title
foreach(XmlNode node in lstTitles)
{
// When you get to a node, look for the element's value
// If you find an element whose value is Her Alibi
if (node.InnerText == "The Distinguished Gentleman")
{
// Create an element named Category
XmlElement elmNew = xmlDoc.CreateElement("Category");
// Create the text of the new element
XmlText txtCatetory = xmlDoc.CreateTextNode("Comedy");
// Get a reference to the parent of the node we have found
XmlNode elmParent = node.ParentNode;
// Add the new element to the node we found
elmParent.AppendChild(elmNew);
// Specify the text of the new node
elmParent.LastChild.AppendChild(txtCatetory);
// Save the file
xmlDoc.Save(strFilename);
}
}
}
Console.WriteLine();
return 0;
}
}
}
Ceci produirait : <?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>
<Category>Comedy</Category>
</Video>
<Video>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
Utilisez la même approche combinée à ce que nous avons appris sur ajouter un article, vous pouvez ajouter un nouvel élément qui a lui-même des noeuds enfants. Voici un exemple : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of nodes whose name is Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// visit each node named Title
foreach(XmlNode node in lstTitles)
{
// When you get to a node, look for the element's value
// If you find an element whose value is "The Day After Tomorrow"
if (node.InnerText == "The Day After Tomorrow")
{
// Create an element named Actors
XmlElement elmNew = xmlDoc.CreateElement("Actors");
// Get a reference to the parent of the node we have found
XmlNode elmVideo = node.ParentNode;
// Add the new element to the node we found
elmVideo.AppendChild(elmNew);
// Create an element as a child of the new element
// Specify its name as Actor
elmNew = xmlDoc.CreateElement("Actor");
// Create the text of the new element
XmlText txtActor = xmlDoc.CreateTextNode("Dennis Quaid");
// Add the new Actor element to the Actors node
elmVideo.LastChild.AppendChild(elmNew);
// Specify the text of the new node
elmVideo.LastChild.LastChild.AppendChild(txtActor);
// In the same way, add the other Actor nodes
elmNew = xmlDoc.CreateElement("Actor");
txtActor = xmlDoc.CreateTextNode("Jake Gyllenhaal");
elmVideo.LastChild.AppendChild(elmNew);
elmVideo.LastChild.LastChild.AppendChild(txtActor);
elmNew = xmlDoc.CreateElement("Actor");
txtActor = xmlDoc.CreateTextNode("Emmy Rossum");
elmVideo.LastChild.AppendChild(elmNew);
elmVideo.LastChild.LastChild.AppendChild(txtActor);
elmNew = xmlDoc.CreateElement("Actor");
txtActor = xmlDoc.CreateTextNode("Dash Mihok");
elmVideo.LastChild.AppendChild(elmNew);
elmVideo.LastChild.LastChild.AppendChild(txtActor);
// Save the file
xmlDoc.Save(strFilename);
}
}
}
Console.WriteLine();
return 0;
}
}
}
Ceci produirait: <?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>
<Category>Comedy</Category>
</Video>
<Video>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
<Actors />
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
<Actors>
<Actor>Dennis Quaid</Actor>
<Actor>Jake Gyllenhaal</Actor>
<Actor>Emmy Rossum</Actor>
<Actor>Dash Mihok</Actor>
</Actors>
</Video>
</Videos>
Vous pouvez également insérer un ou plusieurs éléments comme enfants d'un noeud existant après avoir localisé ce noeud. Voici un exemple : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of nodes whose names are Title
XmlNodeList lstTitles = xmlDoc.GetElementsByTagName("Title");
// visit each node named Title
foreach(XmlNode node in lstTitles)
{
// When you get to a node, look for the element's value
// If you find an element whose value is Her Alibi
if (node.InnerText == "Her Alibi")
{
// Get a reference to the video node that is
// the parent of the video titled Her Alibi
XmlNode elmVideo = node.ParentNode;
// Create a list of the child nodes of the Her alibi video
XmlNodeList lstActors = elmVideo.ChildNodes;
// Visit each item of the collection
// looking for an element named Actors
foreach (XmlNode nodActor in lstActors)
{
// If you find an element named Actors
if (nodActor.Name == "Actors")
{
// Create a new element named Actor
// Specify its name as Actor
XmlElement elmNew = xmlDoc.CreateElement("Actor");
// Create the text of the new element
XmlText txtActor =
xmlDoc.CreateTextNode("Tom Selleck");
// Add the new Actor element to the Actors node
elmVideo.LastChild.AppendChild(elmNew);
// Specify the text of the new node
elmVideo.LastChild.LastChild.AppendChild(txtActor);
// Add other Actor nodes
elmNew = xmlDoc.CreateElement("Actor");
txtActor = xmlDoc.CreateTextNode("Paulina Porizkova");
elmVideo.LastChild.AppendChild(elmNew);
elmVideo.LastChild.LastChild.AppendChild(txtActor);
elmNew = xmlDoc.CreateElement("Actor");
txtActor = xmlDoc.CreateTextNode("William Daniels");
elmVideo.LastChild.AppendChild(elmNew);
elmVideo.LastChild.LastChild.AppendChild(txtActor);
// Save the file
xmlDoc.Save(strFilename);
// Stop, in this example,
// we don't expect another Actors node
break;
}
}
}
}
}
Console.WriteLine();
return 0;
}
}
}
Ceci produirait : <?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>
<Category>Comedy</Category>
</Video>
<Video>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
<Actors>
<Actor>Tom Selleck</Actor>
<Actor>Paulina Porizkova</Actor>
<Actor>William Daniels</Actor>
</Actors>
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
<Actors>
<Actor>Dennis Quaid</Actor>
<Actor>Jake Gyllenhaal</Actor>
<Actor>Emmy Rossum</Actor>
<Actor>Dash Mihok</Actor>
</Actors>
</Video>
</Videos>
Au lieu d'ajouter simplement un nouveau noeud à la fin des noeuds enfants, vous pouvez indiquer n'importe quelle autre position que vous voulez. Par exemple, vous pouvez vouloir que le nouveau noeud précède un noeud enfant existant. Pour soutenir cette opération, la classe XmlNode fournit la méthode InsertBefore (). Sa syntaxe est : public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild); Le premier argument de cette méthode est le nouveau noeud qui sera ajouté. Le deuxième argument est l'enfant de même parent qui succédera le nouveau noeud. Considérer la version suivante de notre fichier Videos.xml : <?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>
<Category>Comedy</Category>
</Video>
<Video>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
<Video>
<Title>Fatal Attraction</Title>
<Director>Adrian Lyne</Director>
<Length>119 Minutes</Length>
<Format>DVD</Format>
<Rating>R</Rating>
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
Imaginer que vous voulez créer un nouvel élément catégorie au-dessous de l'élément Director dont le nom est Adrian Lyne. Vous pouvez d'abord obtenir une liste de videos. À l'intérieur de chaque vidéo, vérifier les noeuds et découvrir si Video a un noeud Director dont le texte est Adrian Lyne. Une fois que vous trouvez ce noeud, vous pouvez ajouter le nouvel élément après lui. Voici un exemple: using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of the videos
XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");
// visit each video
foreach (XmlNode node in lstVideos)
{
// Within a video, create a list of its children
XmlNodeList lstChildren = node.ChildNodes;
// Visit each child node
foreach (XmlNode dir in lstChildren)
{
// If the child node is
// (a director and its name is) Adrian Lyne
if (dir.InnerText == "Adrian Lyne")
{
// Create an element named Category
XmlElement elmNew = xmlDoc.CreateElement("Category");
// Specify the text of the new element
elmNew.InnerText = "Drama";
// Insert the new node below
// the Adrian Lyne node Director
node.InsertAfter(elmNew, dir);
// Save the file
xmlDoc.Save(strFilename);
// Stop
break;
}
}
}
}
Console.WriteLine();
return 0;
}
}
}
Ceci produirait : <?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>
<Category>Comedy</Category>
</Video>
<Video>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
<Video>
<Title>Fatal Attraction</Title>
<Director>Adrian Lyne</Director>
<Category>Drama</Category>
<Length>119 Minutes</Length>
<Format>DVD</Format>
<Rating>R</Rating>
</Video>
<Video>
<Title>The Day After Tomorrow</Title>
<Director>Roland Emmerich</Director>
<Length>124 Minutes</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video>
</Videos>
De la même manière, vous pouvez insérer un nouveau noeud après un enfant d'un enfant (d'un enfant d'un enfant d'un enfant) de n'importe quel noeud. Si vous voulez au nouveau noeud d'être placé après un noeud enfant existant, vous pouvez appeler la méthode XmlNode.InsertAfter (). Sa syntaxe est : public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild);
Si vous avez un noeud que vous ne voulez pas ou n'en avez pas besoin davantage dans le fichier, vous pouvez le supprimer. Pour supprimer un noeud, la classe XmlNode fournit la méthode RemoveChild (). Sa syntaxe est : public virtual XmlNode RemoveChild(XmlNode oldChild); Cette méthode prend comme argument le noeud à supprimer. Si le noeud existe, il serait supprimé et la méthode le renverrait. Si le noeud n'existe pas, rien ne se produirait. Pour utiliser efficacement cette méthode, vous devriez d'abord localiser le noeud particulier que vous voulez supprimer. Vous pouvez le rechercher en utilisant l'une des logiques que nous avons appliquées jusqu'ici. Une fois que vous trouvez le noeud, vous pouvez alors le supprimer. Imaginez aue vous voulez supprimer un noeud dont le nom est Director et dont la valeur est Bruce Beresford. Voici un exemple d'appel cette méthode pour effectuer l'opération : using System;
using System.IO;
using System.Xml;
namespace VideoCollection1
{
class Program
{
static int Main(string[] args)
{
string strFilename = "Videos.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
// Get a reference to the root node
XmlElement elmRoot = xmlDoc.DocumentElement;
// Create a list of the videos
XmlNodeList lstVideos = xmlDoc.GetElementsByTagName("Video");
// visit each video
foreach (XmlNode node in lstVideos)
{
// Within a video, create a list of its children
XmlNodeList lstChildren = node.ChildNodes;
// Visit each child node
foreach (XmlNode dir in lstChildren)
{
// If the child node is Bruce Beresford
if (dir.InnerText == "Bruce Beresford")
{
node.RemoveChild(dir);
// Save the file
xmlDoc.Save(strFilename);
// Stop
break;
}
}
}
}
Console.WriteLine();
return 0;
}
}
}
Pour supprimer tous les noeuds enfants d'un noeud, vous pouvez appeler la méthode XmlNode.RemoveAll (). Sa syntaxe est : public virtual void RemoveAll(); Quand elle est appelée, cette méthode supprimera tous les noeuds enfants, le cas échéant, leur noeud parent. |
|
|
||
| Précédent | Copyright © 2007, Yevol | Suivant |
|
|
||