Modifique o conteúdo existente XML em C#
-
23-09-2019 - |
Pergunta
Objetivo: Planejo criar um arquivo XML com XMLTextWriter e modificar/atualizar algum conteúdo existente com xmlnode selecionSingleNode (), Node.ChildNode [?]. InnerText = STERGING, etc.
Depois que eu criei o arquivo XML com o XMLTextWriter como abaixo.
XmlTextWriter textWriter = new XmlTextWriter("D:\\learning\\cs\\myTest.xml", System.Text.Encoding.UTF8);
Eu pratiquei o código abaixo. Mas não conseguiu salvar meu arquivo 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");
Eu achei que não é bom produzir como o meu caminho. Existe alguma sugestão sobre isso? Não estou claro sobre os conceitos e o uso do XMLTextWriter e XMLNode no mesmo projeto. Obrigado por ler e respostas.
Solução
Bem, se você deseja atualizar um nó em XML, o XmlDocument
está bem - você não precisa usar 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");
Outras dicas
Usando LINQ para XML se você estiver usando a estrutura 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");
Formando um arquivo 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 os nós XML, use o código abaixo
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");
Tente isso. É o código C#.
O XMLTextWriter é geralmente usado para gerar (não atualizar) o conteúdo XML. Quando você carrega o arquivo XML em um XMLDocument, você não precisa de um escritor separado.
Basta atualizar o nó que você selecionou e .Save () que xmldocument.