我正在尝试通过给定的 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: /locations/group[@name="Client:UserData"]/@root
给定值:“\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>
最佳答案
看起来像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;
}
关于c# - 通过XPath写入XDocument的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19631336/