1
votes

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
Can you provide an example of your XPath query, an input sample and the desired output? Can you also elaborate on what you mean by "splitting the XPath"? - Frédéric Hamidi
Look here. - galenus
Unfortunately he's using XPath to write elements which is not what I'm trying to do. - Tobias Valinski

1 Answers

3
votes

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;
}