通过 XPath 写入 XDocument 的属性值
本文关键字:属性 XDocument XPath 写入 通过 | 更新日期: 2023-09-27 18:37:09
我正在尝试通过给定的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''otherDirectory"
预期输出(作为 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;
}