[英]Adding XML nodes into an existing XML config file
我目前有一个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);
我得到这个例外:
此操作将创建结构不正确的文档。
我该如何工作?...谢谢!
不要使用字符串操作(如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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.