Share via

XML - adding an element to parent with attribute...

Havooma 156 Reputation points
2022-04-06T08:59:56.147+00:00

So first of all, please excuse that I may not have my xml terminology correct. Hopefully this is self explanatory!

I have some code that successfully can add an element to an xml file as below:

    Sub add_element(xmlfile, element_name, to_add)

        Dim xmlDoc As New XmlDocument
        xmlDoc.Load(xmlfile)

        Dim xmlRoot As XmlElement = xmlDoc.SelectSingleNode(//myfile/file_map/open_as)
        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

The problem I have is when the parent contains an attribute (think thats the terminology!) such as:

<open_as ID="txt">

What I want to do is add an extension to the <open_as ID="csv"> in the xml listed below. If I use the code above, it just adds to the first 'open as', and I dont know how to define the specific 'open as' to be 'csv'

How can I modify my code to specify the 'csv' open as below and add an element to it???

<myfile>
<notes>notes here>
<file_map>
<open_as ID="txt">
<extension>abc</extension>
<extension>def</extension>
</open_as>
<open_as ID="csv">
<extension>ghi</extension>
<extension>jkl</extension>
</open_as>
</file_map>
</myfile>

Developer technologies | VB

Answer accepted by question author

Viorel 127K Reputation points
2022-04-06T11:15:20.573+00:00

Try a modification:

 _Dim xmlRoot As XmlElement = xmlDoc.SelectSingleNode("//myfile/file_map/open_as_[@ID='csv']")

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.