如何更新xml元素的集合?

时间:2012-10-15 12:24:57

标签: c# xml linq

我是c#中保存reeding xml和linq的绿色。这是我的代码:

    public static void EditConfiguration (DesignConfiguration design)
    {
        XDocument configXml = XDocument.Load(configXMLFileName);
        var updateData = configXml.Root.Elements("Design").Where(element => (String)element.Attribute("name") == design.DesignName).FirstOrDefault();

        if (updateData != null)
        {
            var myElements = updateData.Elements();  //All the elements under th Design node 
            configXml.Save(configXMLFileName);    
       }            
    }

在myElements变量中有以下元素:

<SourceFolder>C:\CSF_Packages</SourceFolder>
<DestinationFolder>C:\Inetpub</DestinationFolder>
<CopyLookups>True</CopyLookups>
<CopyImages>False</CopyImages>
<ImageSourceFolder>None</ImageSourceFolder>
<ImageDesinationFolder>None</ImageDesinationFolder>

我想用设计配置对象中的值更新每个元素。如果我在对象中有一个值但是有这样的值,那就不会那么难了:

design.SourceFolder design.DesitnationFolder

等(就像元素一样)。该对象为上述元素提供了新值。对我来说很明显我应该使用foreach循环但是当我使用它时的结果不是我想要的那个......

这是我的foreach循环:

            foreach (var item in myElements )
            {
                item.SetElementValue("SourceFolder", design.SourceFolder);
            }

在循环中只有一个元素用于演示需要,但我想将更多元素放在循环中。这就是我得到的:

<SourceFolder>C:\CSF_Packages<SourceFolder>C:\CSF_Packages</SourceFolder></SourceFolder>
<DestinationFolder>None<SourceFolder>C:\CSF_Packages</SourceFolder></DestinationFolder>
<CopyLookups>True<SourceFolder>C:\CSF_Packages</SourceFolder></CopyLookups>
<CopyImages>False<SourceFolder>C:\CSF_Packages</SourceFolder></CopyImages>
<ImageSourceFolder>C:\Inetpub<SourceFolder>C:\CSF_Packages</SourceFolder></ImageSourceFolder>
<ImageDesinationFolder>None<SourceFolder>C:\CSF_Packages</SourceFolder></ImageDesinationFolder>

我想:

<SourceFolder>new_value_from the DesignConfiguration object from the SourceFolder property</SourceFolder>
<DestinationFolder>new_value_from the DesignConfiguration object from the Desitnation Folder property</DestinationFolder>
<CopyLookups>new_value_from the DesignConfiguration object from the CopyLookups property</CopyLookups>

依旧...... 请在压力下帮助一个noobie :)非常感谢你。

1 个答案:

答案 0 :(得分:0)

您应该删除子元素,然后将新元素添加到父元素。 试试这些(未经测试):

public static void EditConfiguration (DesignConfiguration design)
{
    XDocument configXml = XDocument.Load(configXMLFileName);
    var updateData = configXml.Root.Elements("Design").Where(element => (String)element.Attribute("name") == design.DesignName).FirstOrDefault();

    if (updateData != null)
    {
        var myElements = updateData.Elements();  //All the elements under th Design node 
        myElements.Remove();
        updateData.SetElementValue("SourceFolder", design.SourceFolder);
        updateData.SetElementValue("DestinationFolder", design.DestinationFolder);
        updateData.SetElementValue("CopyLookups", design.CopyLookups);

        configXml.Save(configXMLFileName);
   }            
}