Best way to read, modify, and write XML

前端 未结 8 2047
灰色年华
灰色年华 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:22

    Here's a tool I wrote to modify an IAR EWARM project (ewp) file, adding a linker define to the project. From the command line, you run it with 2 arguments, the input and output file names (*.ewp).

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Xml;
    
        namespace ewp_tool
        {
            class Program
            {
                static void Main(string[] args)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(args[0]);
    
                    XmlNodeList list = doc.SelectNodes("/project/configuration[name='Debug']/settings[name='ILINK']/data/option[name='IlinkConfigDefines']/state");
                    foreach(XmlElement x in list) {
                        x.InnerText = "MAIN_APP=1";
                    }
    
                    using (XmlTextWriter xtw = new XmlTextWriter(args[1], Encoding.UTF8))
                    {
                        //xtw.Formatting = Formatting.Indented; // leave this out, it breaks EWP!
                        doc.WriteContentTo(xtw);
                    }
                }
            }
        }
    

    The structure of the XML looks like this

        
        
          2
          
            Debug
            
              ARM
            
            1
    
             ...
    
            
              ILINK
              0
              
    
                ...
    
                
    

提交回复
热议问题