VB Add an attribute to xml

Havooma 156 Reputation points
2022-04-19T14:00:50.267+00:00

I have some working code that can add an elememnt to an xml file:

    Sub add_element_single(xmlfile, element_name, to_add, parentelement)

        'Add a single element to a parent.  

        Dim xmlDoc As New XmlDocument
        xmlDoc.Load(xmlfile)

        Dim xmlRoot As XmlElement = xmlDoc.SelectSingleNode(parentelement)
        Dim xmlChild As XmlElement = xmlDoc.CreateElement(element_name)

        xmlChild.InnerText = to_add
        xmlRoot.AppendChild(xmlChild)

        Try
            xmlDoc.Save(xmlfile)
        Catch ex As Exception
            MsgBox("Exception: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

That works great but Id like to use it to add a new element with attribute (if thats the correct terminology). For example, add a new house to this:

<houses>
<this ID="house1">
<windows>set1</windows>
<windows>set4</windows>
</this >
<this ID="house2">
<windows>set14</windows>
<windows>set15</windows>
</this >
</houses>

to create something like this:

<houses>
<this ID="house1">
<windows>set1</windows>
<windows>set4</windows>
</this >
<this ID="house2">
<windows>set14</windows>
<windows>set15</windows>
</this >
<this ID="house3">
<windows>set7</windows>
<windows>set22</windows>
</this >

</houses>

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

Accepted answer
  1. Michael Taylor 51,346 Reputation points
    2022-04-19T14:35:02.427+00:00

    Adding an attribute to an existing element (which it will be once you create it) is simply a matter of using the SetAttributes method.

       Dim xmlChild As XmlElement = xmlDoc.CreateElement(element_name)  
       xmlChild.SetAttribute("id", id.ToString())  
    

    Have the ID passed as a parameter to your method.

       Sub add_element_single(xmlfile, element_name, to_add, id, parentelement)  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,361 Reputation points
    2022-04-19T14:43:16.707+00:00

    Using XElement instead of XMLDocument,

            Dim myXML As XElement
            ' myXML = XElement.Load("path here")
            ' for testing use literal
            myXML = <houses>
                    </houses>
    
            Dim id As Integer = 1
            Dim wset As New List(Of String) From {"setA", "setB", "setZ"}
            For id = 1 To 3
                myXML.Add(<this ID=<%= "house" & id.ToString %>>
                              <%= From foo In wset
                                  Select <windows><%= foo %></windows>
                              %>
                          </this>)
            Next
    
            ' myXML.Save("path here")
    
    0 comments No comments