如何使用XMLWriter类在XMl文件中追加内容

本文关键字:追加 文件 XMl 何使用 XMLWriter 类在 | 更新日期: 2023-09-27 17:53:43

如何在XMl文件中添加XMLWriter类

XmlWriterSettings xmlFragments = new XmlWriterSettings();
            xmlFragments.Indent = true ;
            XmlTextWriter xWriter = new XmlTextWriter(_logFilePath, null);
            xWriter.WriteStartDocument();//starting document
            xWriter.WriteStartElement("values");//starting parent node
            xWriter.WriteStartElement("values1");//1st child node
            xWriter.WriteAttributeString("id", "200");//attributes of child node
            xWriter.WriteAttributeString("name", "ABCD");
            xWriter.WriteString("ISO Company");//innertext
            xWriter.WriteEndElement();
            xWriter.WriteStartElement("num");//2nd child node
            xWriter.WriteAttributeString("more", "500");
            xWriter.WriteAttributeString("less", "101");
            xWriter.WriteString("numeric");
            xWriter.WriteEndElement();
            xWriter.WriteStartElement("r", "runnnig", "");//3rd child node
            xWriter.WriteAttributeString("fast", "500km");
            xWriter.WriteAttributeString("slow", "10km");
            xWriter.WriteString("killometers");
            xWriter.WriteEndElement();
            xWriter.WriteStartElement("character");
            xWriter.WriteAttributeString("char", "a");
            xWriter.WriteAttributeString("another", "b");
            xWriter.WriteEndElement();
            xWriter.WriteEndElement();
            xWriter.WriteEndDocument();
            xWriter.Close();

我试图在xmlwriter中加载xml文件,但这个类覆盖了以前的标签,但我不想覆盖标签。

如何使用XMLWriter类在XMl文件中追加内容

可以通过XmlDocument解决。

  XmlDocument doc = new XmlDocument();
  doc.Load("test.xml");
  XmlElement el = doc.CreateElement("child");
  el.InnerText = "This row is being appended to the end of the document.";
  doc.DocumentElement.AppendChild(el);
  doc.Save("test.xml");