2015-07-21 84 views
0

我现在有一个包含这样的节点(在XML文件中)的XML文件:添加XML节点到现有的XML配置文件

<StationsSection> 
    <Stations /> 
</StationsSection> 

我需要使它成为追加到它这样的:

<StationsSection> 
    <Stations> 
     <add Comment="I'm here!" DestinationFolderPath="C:\" FtpHostname="ftp://upload.domain.com/" FtpFolderPath="myFolder/" FtpUsername="555" FtpPassword="secret!!!" FtpTimeoutInSeconds="20" /> 
     <add Comment="I'm here!" DestinationFolderPath="C:\" FtpHostname="ftp://upload.domain.com/" FtpFolderPath="myFolder/" FtpUsername="555" FtpPassword="secret!!!" FtpTimeoutInSeconds="20" /> 
    </Stations> 
</StationsSection> 

这些数据(“注释”,“DestinationFolderPath”等),目前保存在自定义对象的泛型列表 - 所谓的“updatedStations”。当我尝试添加它们是这样的:

foreach (var station in updatedStations) 
{ 
    XElement updatedStation = new XElement("add", elementToAdd); // "elementToAdd" has a value 
    xml.Add(updatedStation); // "xml" is an XDocument 
} 

...那 “updatedStation” 变量有这个值:

<add>Comment="I'M HERE!" DestinationFolderPath="C:\" FtpHostname="myFolder/" FtpFolderPath="ftp://upload.domain.com/" FtpUsername="555" FtpPassword="secret!!!" FtpTimeoutInSeconds="20"</add> 

当尝试这一行:

xml.Add(updatedStation); 

我得到此例外:

此操作会创建一个不正确的str制作文件。

我该如何得到这个工作?...谢谢!

回答

1

请勿使用字符串操作(如updatedStation)。下面是一个Linq2Xml + XPath的一个例子(假设你可以得到的updatedStation的部分)

var xDoc = XDocument.Load(filename); 
var st = xDoc.XPathSelectElement("//StationsSection/Stations"); 
st.Add(new XElement(
      "add", 
      new XAttribute("Comment","I'm here"), 
      new XAttribute("DestinationFolderPath","C:\\") ) 
     ); 

PS:不要忘了,包括名字空间

using System.Xml.XPath; 
using System.Xml.Linq;