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>
3
  • 2
    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"? Commented Oct 28, 2013 at 9:40
  • Look here. Commented Oct 28, 2013 at 9:50
  • Unfortunately he's using XPath to write elements which is not what I'm trying to do. Commented Oct 28, 2013 at 9:55

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Since XPathEvaluate returns object you can't call OfType<T>() on it. Another cast returns null for attr
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.