Home > Software design >  Adding an element to parent with attribute
Adding an element to parent with attribute

Time:04-07

So first, 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 that's 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 don't 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>

CodePudding user response:

Some ideas using XElement and LINQ, first the data

    Dim test As XElement
    'to load from file
    ' test = XElement.Load("path here")

    'for testing use literal
    test = <myfile>
               <notes>notes here</notes>
               <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>

Then the code

    'select one open node with ID = csv
    Dim nd As XElement
    nd = (From el In test...<open_as>
           Where el.@ID = "csv"
           Select el).FirstOrDefault

    'add extension node
    Dim to_add As String = "xyz"
    nd.Add(<extension><%= to_add %></extension>)

    Stop ' examine test

CodePudding user response:

Turns out this will do it:

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

  • Related