Modifier le contenu existant XML en C #
-
23-09-2019 - |
Question
Objet: [?].. Je prévois de créer un fichier XML avec XmlTextWriter et Modifier / Mettre à jour un certain contenu existant avec XmlNode SelectSingleNode (), node.ChildNode InnerText = someting, etc
Après avoir créé le fichier XML avec XmlTextWriter comme ci-dessous.
XmlTextWriter textWriter = new XmlTextWriter("D:\\learning\\cs\\myTest.xml", System.Text.Encoding.UTF8);
Je pratiquais le code ci-dessous. Mais pas enregistrer mon fichier XML.
XmlDocument doc = new XmlDocument();
doc.Load("D:\\learning\\cs\\myTest.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode;
myNode= root.SelectSingleNode("descendant::books");
....
textWriter.Close();
doc.Save("D:\\learning\\cs\\myTest.xml");
Je l'ai trouvé est pas bon de produire comme mon chemin. Y at-il suggéré à ce sujet? Je ne suis pas clair sur les concepts et l'utilisation des deux XmlTextWriter et XmlNode dans le même projet. Merci pour la lecture et les réponses.
La solution
Eh bien, si vous souhaitez mettre à jour un nœud en XML, le XmlDocument
est très bien -. Vous ne devez pas utiliser XmlTextWriter
XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
Autres conseils
Utilisation LINQ to XML si vous utilisez Framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
Formant un fichier XML
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
Pour modifier les nœuds Xml utilisent le code ci-dessous
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Essayez ceci. Il est le code C #.
Le XmlTextWriter est habituellement utilisé pour générer du contenu XML (non mise à jour). Lorsque vous chargez le fichier XML dans un XmlDocument, vous n'avez pas besoin d'un auteur distinct.
Il suffit de mettre à jour le nœud que vous avez sélectionné et .Save () qui XmlDocument.