Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select XML node by attribute value

Tags:

.net

xml

f#

<location>
  <hotspot name="name1" X="444" Y="518" />
  <hotspot name="name2" X="542" Y="452" /> 
  <hotspot name="name3" X="356" Y="15" />
</location>

I have a point variable and I need to select the node with its coordinates, then change an attribute value. I want to do something similar to:

let node = xmld.SelectSingleNode("/location/hotspot[@X='542' @Y='452']")
node.Attributes.[0].Value <- "new_name2"

but taking attributes value by a variable (variable_name.X / variable_name.Y).

like image 946
Frank Lioty Avatar asked Aug 04 '26 21:08

Frank Lioty


2 Answers

It was really easy. Supposing I want to modify the first attribute in my node:

let node = xmld.SelectSingleNode("/location/hotspot[@X='" + string(current.X) + "'] [@Y='" + string(current.Y) + "']")
node.Attributes.[0].Value <- v

where "current" is my variable ;)

like image 147
Frank Lioty Avatar answered Aug 07 '26 18:08

Frank Lioty


Personally I would use LINQ to XML:

var doc = XDocument.Load(...);
var node = doc.Root
              .Elements("hotspot")
              .Single(h => (int) h.Attribute("X") == x &&
                           (int) h.Attribute("Y") == y);

Note that you should use SingleOrDefault if there may not be any matching elements, or First / FirstOrDefault if there could be multiple matches.

Once you've found the right hotspot node, you can set the attributes easily:

node.SetAttributeValue("X", newX);
node.SetAttributeValue("Y", newY);
like image 42
Jon Skeet Avatar answered Aug 07 '26 19:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!