2010-10-17 39 views
0

我有一个XML,如下所示。更新XElement(或克隆的XElement)的子项属性

<AFConfig> 
<Geographies> 
    <Geography id="Place1" description="NicePlace"> 
    <MetaData> 
    <Services> 
    <Service> 
    ... 
    ... 
    </Service> 
    </Services> 
    </MetaData> 
    <Systems> 
    <DefaultSystem systemName="SYSONE" server=http"//192.168.0.0" /> 
    </Systems> 
    </Geography> 
<Geographies> 
</AFConfig> 

我想要做的是这样的。

  1. 克隆元素地理学,并将其与新的价值
  2. 添加作为同级(即孩子地理学)
  3. 更新“ID”,“说明”用新值 和
  4. 更新SYSTEMNAME

我的代码。

XDocument xd_Document = XDocument.Load(s_FileName); 
XElement xe_Element = (from xe in xd_Document.XPathSelectElements(s_Element) 
         where xe.Attribute(s_IdAttr).Value == s_Value 
         select xe).SingleOrDefault(); 
XElement xe_NewElement = CloneElement(xe_Element) 
foreach(KeyValuePair<string, string> s in d_AttrValue) 
    xe_NewElement.Attribute(s.Key).Value = d_AttrValue[s.Key]; 
xe_Element.Parent.Add(xe_NewElement); 
xd_Document.Save(s_destFileName); 

我传递给该方法的以下参数 串s_FileName,串s_destFileName,串s_Element,串s_IdAttr,串s_Value,字典d_AttrValue

有了这个代码,我能够修改id和描述属性。

问题:如何使用值修改DefaultSystem属性systemName?

注意:我有相同的代码来修改现有元素无法创建新元素。再一次,我遇到了同样的问题。通用的解决方案将是首选。

回答

0
xe_NewElement.Element("Systems") 
    .Element("DefaultSystem") 
    .Attribute("systemName") 
    .Value = "Enter your value here"; 

我相信应该做你需要的。

编辑:

var attribute = ((IEnumerable)xe_NewElement.XPathEvaluate("Systems/DefaultSystem/@systemName")) 
    .Cast<XAttribute>().FirstOrDefault(); 

attribute.Value = “请输入您的值”;

应该让你通过传递xpaths和values的列表。

+0

安迪:谢谢。但是,我的代码是Function的一部分。而且我不想硬编码子元素名称。有没有办法解决这个问题呢? – Kanini 2010-10-17 17:19:55

+0

我编辑了我的答案以包含更通用的解决方案。虽然不太好,但必须有更好的解决方案。 – 2010-10-17 17:50:24

+0

Andy:上面编辑的一段代码出现错误:使用泛型类型'System.Collections.Generic.IEnumerable '需要'1'类型参数 – Kanini 2010-10-18 07:00:49