Visual Basic how to update an xml attribute

Havooma 156 Reputation points
2022-04-30T12:48:41.837+00:00

I have searched everywhere but cant find something that works! I have some xml which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<times>
<given type="type1">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
<given type = "type2">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
<given type = "type3">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
</times>

I want to change the name of "type2" to "typeX". I have some code below but it doesnt work. Any ideas would be most welcome!

 Dim newValue As String
 Dim xmlDoc = New XmlDocument

xmlDoc.Load(xmlfile)

 Dim attr As XmlAttribute

 attr = xmlDoc.SelectSingleNode("/given[@type='type2']")
 attr.Value = "typeX"

 xmlDoc.Save(xmlfile)
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,562 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Havooma 156 Reputation points
    2022-04-30T19:06:50.827+00:00

    So I worked it out after all! Here is the solutions:

            Dim xmlDoc = New XmlDocument  
            xmlDoc.Load(xmlfile)  
      
      
            Dim attr As XmlAttribute = DirectCast(xmlDoc.SelectSingleNode(source_attribute_path), XmlAttribute)  
            attr.Value = new_attribute_name  
      
            xmlDoc.Save(xmlfile)  
    

    Where the source_attribution_path is

    "//times/given[@type ='type2']/@type "

    0 comments No comments

  2. Dewayne Basnett 1,041 Reputation points
    2022-05-02T13:34:30.527+00:00

    Another approach using XElement and LINQ

            Dim xmlFile As XElement
    
            xmlFile = XElement.Load("path here")
            'for testing
            xmlFile = <times>
                          <given type="type1">
                              <data1>"data1 here</data1>
                              <data2>"data2 here"</data2>
                          </given>
                          <given type="type2">
                              <data1>"data1 here</data1>
                              <data2>"data2 here"</data2>
                          </given>
                          <given type="type3">
                              <data1>"data1 here</data1>
                              <data2>"data2 here"</data2>
                          </given>
                      </times>
    
            Dim xelND As XElement
            xelND = (From el In xmlFile.<given>
                       Where el.@type = "type2"
                       Select el
                       Take 1).FirstOrDefault
    
            If xelND IsNot Nothing Then xelND.@type = "typeX"
    
            xmlFile.Save("path here")
    
    0 comments No comments