【问题标题】:Updating Child's Attribute of a XElement (or a Cloned XElement)更新 XElement(或克隆的 XElement)的子属性
【发布时间】:2010-10-17 17:03:50
【问题描述】:

我有一个如下的 XML。

<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. 克隆元素 Geography 并将其添加为 Sibling(即,Child to Geographies)
  2. 用新值更新“id”、“description” 和
  3. 用新值更新系统名称

我的代码。

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 和 description 属性。

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

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

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:
    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 = "在此处输入您的值";

    应该允许您通过传入 xpath 和值的列表来一般地这样做。

    【讨论】:

    • 安迪:谢谢。但是,我的代码是函数的一部分。而且我不希望对子元素名称进行硬编码。有没有办法,可以说是通用的方法来解决这个问题?
    • 我已经编辑了我的答案以包含一个更通用的解决方案。虽然不好看,但一定有更好的解决方案。
    • Andy:上面编辑的代码出现了一个错误,即使用泛型类型 'System.Collections.Generic.IEnumerable' requires '1' type arguments
    • 您可能需要使用 System.Generic 添加;给你的cs文件。
    • 安迪:谢谢。我会检查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多