Ho usato il seguente codice per creare un file XML:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("School"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
Ho bisogno di inserire i nodes creando dynamicmente la seguente struttura:
David Smith ... David Smith ...
Come posso farlo? I valori di “FirstName” e “LastName” devono essere letti dalla tastiera e i valori possono essere inseriti in qualsiasi momento, ovviamente sotto esistenti.
puoi usare Linq Xml
XDocument doc = XDocument.Load(xmlFilePath); XElement school = doc.Element("School"); school.Add(new XElement("Student", new XElement("FirstName", "David"), new XElement("LastName", "Smith"))); doc.Save(xmlFilePath);
modificare
se vuoi aggiungere Elemento a
Esistente, basta aggiungere un Attributo prima
school.add(new XElement("Student", new XAttribute("ID", "ID_Value"), new XElement("FirstName", "David"), new XElement("LastName", "Smith")));
Quindi puoi aggiungere ulteriori dettagli allo
esistente per ricerca -> ottieni -> aggiungi
XElement particularStudent = doc.Element("School").Elements("Student") .Where(student => student.Attribute("ID").Value == "SearchID") .FirstOrDefault(); if(particularStudent != null) particularStudent.Add(new XElement("","");
finalmente ci sono riuscito 🙂
if (!File.Exists("Test.xml")) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("School"); xmlWriter.WriteStartElement("Student"); xmlWriter.WriteElementString("FirstName", firstName); xmlWriter.WriteElementString("LastName", lastName); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); xmlWriter.Close(); } } else { XDocument xDocument = XDocument.Load("Test.xml"); XElement root= xDocument.Element("School"); IEnumerable rows = root.Descendants("Student"); XElement firstRow= rows.First(); firstRow.AddBeforeSelf( new XElement("Student", new XElement("FirstName", firstName), new XElement("LastName", lastName))); xDocument.Save("Test.xml"); }
Lascia che ti dia un suggerimento. Quando crei il tuo file xml, dai ai tuoi studenti un id unico come questo:
// to store the id variable, if you create more than one student you can increase it count = 0; xmlWriter.WriteStartElement("School"); xmlWriter.WriteAttributeString("ID",count.ToString()); xmlWriter.WriteEndElement();
Quindi, quando devi aggiungere informazioni a questo studente, puoi ottenere ID
, Firstname
e Lastname
e puoi modificare il tuo file XML con LINQ in XML in questo modo:
int id = Convert.ToInt32(txtStudentId.Text); XDocument xDoc = XDocument.Load("Test.xml"); XElement student = xDoc.Descendants("Student").Where(x => (string) x.Attribute("ID") == id).FirstOrDefault(); if (student != null) { string firstName = txtFirstName.Text; string lastName = txtLastName.Text; XElement first = new XElement("FirstName", firstName); XElement last = new XElement("LastName", lastName); student.Add(first); student.Add(last); xDoc.Save("Test.xml"); }
So che hai chiesto XmlWriter, ma credo che puoi ottenere questo usando meno codice con XDocument. Ecco la mia soluzione:
var filePath = "path/XmlFile.xml"; var xmlDoc = XDocument.Load(filePath); var parentElement = new XElement("Student"); var firstNameElement = new XElement("FirstName", firstNameVariable); var lastNameElement = new XElement("LastName", lastNameVariable); parentElement.Add(firstNameElement); parentElement.Add(lastNameElement); var rootElement = xmlDoc.Element("School"); rootElement?.Add(parentElement); xmlDoc.save();
Questo è basato sulla seguente struttura XML e sarà aggiunto a ...
:
John Johnson ...
Spero che questo ti aiuti!
Ho un suggerimento per la prossima volta:
string nameFile = "Test.xml"; bool newFile = false; if (!File.Exists(nameFile)) { newFile = true; XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("School"); xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings)) } else { doc = new XmlDocument(); doc.Load(nameFile); // Create a XPathNavigator // You can go where you want to add // In this case it is just after last child of the roor XPathNavigator navigator = doc.CreateNavigator(); navigator.MoveToChild("School", ""); xmlWriter = navigator.AppendChild(); } // From here you can work only with xmlWriter, // One will point on a file and the other on the stream of xmlDocument // So you will need to save the document in the second choise xmlWriter.WriteStartElement("Student"); xmlWriter.WriteElementString("FirstName", firstName); xmlWriter.WriteElementString("LastName", lastName); xmlWriter.WriteEndElement(); // End document / close or save. if (newFile) xmlWriter.WriteEndDocument(); xmlWriter.Close(); if (!newFile) doc.Save(nameFile);
Dovrebbe funzionare. 🙂