c# 代码创建xml文件

 #region /***创建文件***/
        
public void   CreateXmlFile(string strFilePath,string[] strElement,string[] strElementString)
        
{    
            
try
            
{
                XmlDocument xmldoc 
= new XmlDocument( ) ;
                XmlDeclaration   xn   
=  xmldoc.CreateXmlDeclaration("1.0","gb2312",null);   
                xmldoc.AppendChild(xn);
    
                
//加入一个根元素
                XmlElement  xmlelem = xmldoc.CreateElement ( "" , "myinfo" , "" ) ;
                xmldoc.AppendChild(xmlelem) ;
                XmlElement xe1
=xmldoc.CreateElement("user"); 
   
                XmlElement xesub2
=xmldoc.CreateElement(strElement[0].ToString());
                xesub2.InnerText
=strElementString[0].ToString();
                xe1.AppendChild(xesub2);
        
                XmlElement xesub3
=xmldoc.CreateElement(strElement[1].ToString());
                xesub3.InnerText
=strElementString[1].ToString();
                xe1.AppendChild(xesub3);

                xmldoc.ChildNodes.Item(
1).AppendChild (xe1) ;
 
                
//保存创建好的XML文档
                try
                
{
                    xmldoc.Save(strFilePath) ; 
                }

                
catch (Exception e )
                
{
                    
throw e;
                }

                
    
            }

            
catch (Exception err)
            
{
                
throw err;    
            }

            
        }


        
#endregion

给xml添加"<?xml version="1.0" encoding="gb2312"?> "格式:
XmlDocument xmldoc = new XmlDocument( ) ;
    XmlDeclaration   xn   =  xmldoc.CreateXmlDeclaration("1.0","gb2312",null);  
    xmldoc.AppendChild(xn);

最后创建好的xml文件:
<?xml version="1.0" encoding="gb2312"?>
<myinfo>
  <user>
   ***
  </user>
</myinfo>

原文地址:https://www.cnblogs.com/liufei88866/p/1249496.html