<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).
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 ;)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With