Richard Richard - 3 months ago 71 Question

Edit XML tag by attribute

I have a XML document which looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Data key="dailyKey">19283</Data>

And in my program I want to change the value from "
" by the attribute "dailyKey"

I have tried to understand myself on this but cannot figure out how to edit TAG by ATTRIBUTE

Please help, Richard


You could use XPath expressions and the SelectSingleNode method like this:

Dim node = xmlDoc.SelectSingleNode("//data[@key=""daileyKey""]")

Then you can modify the value of node as you wish to. You can find more XPath examples at MSDN.

The workflow in its entirety would be:

1. Load the XML Document for manipulation

You can use the XmlDocument class to load (and subsequently save) your XML Document like this:

Dim xmlDoc As New XmlDocument()
xmlDoc.Load("<Here goes your url // You can also feed in a stream to this method>")

2. Locate the node you want to modify

As mentioned earlier, use the SelectSingleNode function to locate the node you are trying to modify the value of. It takes an XPath expression.

Dim node = xmlDoc.SelectSingleNode("//data[@key=""daileyKey""]")

3. Modify the node

You can now edit the node (tag) in whatever way you wish. It seems you want to edit the contained value. Do it by changing the Value property of the XmlNode:

node.Value = 224062 'Random value. Change to suit your needs.

4. Save the XML Document (Obviously :P)