Best way to read, modify, and write XML

前端 未结 8 2006
灰色年华
灰色年华 2021-02-05 10:39

My plan is to read in an XML document using my C# program, search for particular entries which I\'d like to change, and then write out the modified document. However, I\'ve bec

8条回答
  •  一生所求
    2021-02-05 11:25

    Are the documents you are processing relatively small? If so, you could load them into memory using an XmlDocument object, modify it, and write the changes back out.

    XmlDocument doc = new XmlDocument();
    doc.Load("path_to_input_file");
    // Make changes to the document.
    using(XmlTextWriter xtw = new XmlTextWriter("path_to_output_file", Encoding.UTF8)) {
      xtw.Formatting = Formatting.Indented; // optional, if you want it to look nice
      doc.WriteContentTo(xtw);
    }
    

    Depending on the structure of the input XML, this could make your parsing code a bit simpler.

提交回复
热议问题