【问题标题】:Adding XML nodes into an existing XML config file将 XML 节点添加到现有 XML 配置文件中
【发布时间】: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);

我得到了这个例外:

此操作会创建结构不正确的文档。

我怎样才能让它工作?...谢谢!

【问题讨论】:

    标签: c# xml winforms


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多