c# - 通过XPath写入XDocument的属性值

标签 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: /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/

相关文章:

c# - Assert.True 未通过测试

xpath - 我如何将字符串从xpath放入richler URL

c# - dotnet run 给了我 "*** stack smashing detected ***: <unknown> terminated"

xml - 如何在 XSD 中处理具有不同 URI 的多个命名空间

java - 使用 JDOM 解析 XML 文件,出现错误 StackOverflowError

php - 将 XML 数据发布到 MySQL 会返回错误?

xpath - Marklogic-如何在cts:uris中添加集合名称

python - 两个相同的 AutomationID 使用 xpath python 和 appium

c# - 使用枚举 C# 为具体类创建接口(interface)?

javascript - 如何在angularjs中使用文本框值检查表格?