通过XPath写入XDocument的属性值

时间:2013-10-28 09:38:09

标签: c# xml xpath linq-to-xml

我正在尝试通过给定的XPath将属性值写入现有的XDocument。但似乎唯一的方法是获取一个元素然后调用该属性。是否有任何方法直接编写属性(在我的情况下,没有将给定的XPath拆分为“/ locations / group [@ name =”Client:UserData“]”用于选择元素和“/ @ root”用于从中获取属性XElement对象)。

给定XML(作为XDocument):

<locations>
  <group name="Client:UserData" root="\\appserver\Data" required="true">
    <path name="some name" path="~\directory\file" required="false" autoCreate="false" />
  </group>
</locations>

给出XPath: /位置/组[@名称= “客户:的UserData”] / @根

给定值:“\ appserver \ anotherDirectory”

预期输出(作为XDocument):

<locations>
  <group name="Client:UserData" root="\\appserver\anotherDirectory" required="true">
    <path name="some name" path="~\directory\file" required="false" autoCreate="false" />
  </group>
</locations>

1 个答案:

答案 0 :(得分:2)

看起来XPathEvaluate()会解决您的问题:

using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

foreach (XAttribute attr in ((IEnumerable)
         yourDocument.XPathEvaluate(yourXPath)).OfType<XAttribute>()) {
    attr.Value = yourValue;
}