0

How can I add an attribute to an existing XML element in VB.Net?

I open a file then I read the XML data from it:

Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNodeList
Dim source As String = $"C:\sample.xml"
Dim fs As New FileStream(source, FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
xmlnode = xmldoc.GetElementsByTagName("student")

How do I add an "id" attribute to each "student" element?

Marwan مروان
  • 2,163
  • 8
  • 30
  • 40
  • Have you looked at the documentation for `XmlElement`? You should be able to find what you're looking for there. Iteration over the list of nodes is trivial (with the caveat that you won't be able to infer the type of the iteration variable because the XML API you're using predates generics in .NET and thus the list exposes `IEnumerable` rather than `IEnumerable(Of T)`). – Craig Oct 27 '20 at 12:25
  • Just use XElement. See answer below. – dbasnett Oct 27 '20 at 13:47
  • Thank you both for your suggestions. I have been having trouble finding reliable examples for XML in VB.Net – Marwan مروان Oct 28 '20 at 06:25

1 Answers1

0

Using XElement

    Dim xe As XElement
    Dim source As String = $"C:\sample.xml"
    xe.Load(source)
    For Each el As XElement In xe...<student>
        el.@your_attribute_here = "value"
    Next
dbasnett
  • 11,334
  • 2
  • 25
  • 33
  • Thanks for the suggestion. I will look into this right away. Do you have any suggestions for good resources with code examples for XElement? – Marwan مروان Oct 28 '20 at 06:26
  • https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/xml/creating-xml – dbasnett Oct 28 '20 at 15:02