Skip to main content
 首页 » 编程设计

c#之如何在现有的完全空的 .xml 文件中写入内容

2024年02月06日12yxwkf

如何在现有的完全空的 .xml 文件中写入内容? 我正在创建一个名为 newXML.xml 的新文件,并将其路径存储在一个字符串中,如下所示:

File.Create(Application.StartupPath + @"newXML.xml");    
string path=Application.StartupPath + @"newXML.xml"; 

现在我有一些带有 xml 标签的 xml 数据,我想将这些数据存储到一个字符串中,并将这些数据写入我创建的名为 newXML.xml 的新文件中。

我要存储在字符串中的数据如下...

<configuration> 
<system.runtime.remoting> 
<application name="Server"> 
     <client> 
     </client> 
</application> 
</system.runtime.remoting> 
</configuration> 

我该怎么做?

请您参考如下方法:

看看 XDocument类。

XDocument xml = new XDocument( 
    new XElement("configuration", 
        new XElement("system.runtime.remoting", 
            new XElement("application", 
                new XAttribute("name", "Server"), 
                new XElement("client"))))); 
xml.Save(//Stream to save file);