【发布时间】:2015-07-21 18:25:45
【问题描述】:
我目前有一个 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>
该数据(“Comment”、“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);
我得到了这个例外:
此操作会创建结构不正确的文档。
我怎样才能让它工作?...谢谢!
【问题讨论】: