Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an XElement, how do I retrieve a reference to another relative XElement/Xattribute given an XPath?

Given the following XML:

<SomeXML>
    <Element1>
        <Element2 Attribute3="Value4" />
    </Element1
</SomeXML>

... and an XElement reference to 'SomeElement' and an XPath 'Element1/Element2/@Attribute3'

How do I retrieve a reference to Attribute3 so that I may alter it's value (using the Xpath)?

The XPath is to be a retrieved setting and thus is my only way of locating the node in question.

like image 761
Rory Becker Avatar asked Dec 29 '22 16:12

Rory Becker


2 Answers

Add using System.Xml.XPath to the code file where you need to do this.

Then you can use code like this:-

 var attrib3 = someElement.XPathEvaluate("Element1/Element2/@Attribute3") as XAttribute;
 if (attrib3 != null)
     attrib3.Value = "new value";
like image 165
AnthonyWJones Avatar answered Jan 01 '23 09:01

AnthonyWJones


using System.Xml.XPath

and the extension method XPathSelectElement on your XElement

like image 29
Gregoire Avatar answered Jan 01 '23 09:01

Gregoire