1

I'm trying to write an attribute value to an existing XDocument via a given XPath. But it seems the only way to do this is getting an element and then calling the attribute. Is there any way to write a attribute directly (in my case without splitting the given XPath to "/locations/group[@name="Client:UserData"]" for selecting the element and "/@root" for getting the attribute from the XElement object).

given XML (as XDocument):

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

given XPath: /locations/group[@name="Client:UserData"]/@root

given value: "\appserver\anotherDirectory"

expected output (as 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 Answers1

3

It looks like XPathEvaluate() would solve your problem:

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

foreach (XAttribute attr in ((IEnumerable)
         yourDocument.XPathEvaluate(yourXPath)).OfType<XAttribute>()) {
    attr.Value = yourValue;
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • Since XPathEvaluate returns object you can't call OfType() on it. Another cast returns null for attr – Tobias Valinski Oct 28 '13 at 10:20
  • @Tobias, you're right, I forgot a cast to `IEnumerable`. The updated code should work unless your XPath query happens to return a primitive type instead of a node set. – Frédéric Hamidi Oct 28 '13 at 10:31