Modificar XML contenido existente en C #
-
23-09-2019 - |
Pregunta
Objetivo: [?].. I plan para crear un archivo XML con XmlTextWriter y modificar / actualizar algunos contenidos con una XmlNode SelectSingleNode (), node.ChildNode InnerText = algo parecido, etc.
Después de crear el archivo XML con XmlTextWriter como a continuación.
XmlTextWriter textWriter = new XmlTextWriter("D:\\learning\\cs\\myTest.xml", System.Text.Encoding.UTF8);
Me practica el código de abajo. Pero no para salvar a mi archivo 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");
He encontrado que no es bueno para producir como mi manera. ¿Hay alguna sugerencia al respecto? No estoy claro acerca de los conceptos y el uso de ambos XmlTextWriter y XmlNode en el mismo proyecto. Gracias por leer y respuestas.
Solución
Bueno, Si desea actualizar un nodo en XML, el XmlDocument
está bien -. No es necesario utilizar 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");
Otros consejos
El uso de LINQ to XML si está utilizando 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");
La formación de un archivo 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();
Para editar los nodos XML utilizan el siguiente código
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");
Probar. Es de código C #.
El XmlTextWriter se utiliza generalmente para generar (no actualizar) el contenido de XML. Cuando se carga el archivo XML en un XmlDocument, usted no necesita un escritor independiente.
Sólo actualizar el nodo que haya seleccionado y .Save () que XmlDocument.