0

我对在 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>

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

设计.SourceFolder 设计.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>

等等...请帮助有压力的菜鸟 :) 非常感谢。

4

1 回答 1

0

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

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);
   }            
}
于 2012-11-08T15:58:43.900 回答