Code to insert an XML line VB.NET 2005

arthurh88
arthurh88 used Ask the Experts™
on
Here is my sample XML file
<doc>
  <total_loops value="0" />
  <total_cmds value="0" />
  <total_macros value="5" />
  <loop1 name="MyLoop1" type="Min" length="20" data="Sample XML File" />
  <loop2 name="MyLoop2" type="Sec" length="50" data="some more data" />
  <macro1 name ="My Macro" Value ="100-245,C,W1,200-340,DC" />
</doc>

Im trying to get this function to work in order to insert a new nodelist after any particular nodename

Public Function InsertNode(ByVal FilePath As String, ByVal NodeXML As String, byVal AfterThisNode as string) As Boolean
        Dim doc As New System.Xml.XmlDocument
        doc.Load(FilePath)
        Dim nd As System.Xml.XmlNode
        nd = doc.DocumentElement.GetElementsByTagName(AfterThisNode).Item(0)
        If nd Is Nothing Then 'could not find the node to insert after, then just add to the bottom
        'TO DO:  need code to add the line of XML to the end of the document
        ELSE 'found the node, now insert new line after
        TO DO:  need code to insert XML line after found node
        End If
        doc.Save(FilePath)
        Return True
    End Function
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
I believe that you could just use this:

doc.InsertAfter(myNewNode, nd)



Author

Commented:
im trying to insert a node list.  
for example,  <loop1a name="MyLoop1a" type="Sec" length="34" data="data" /> to be inserted after loop1

doc.InsertAfter(myNewNode, nd) returns an error.  How do I set myNewNode to equal  "<loop1a name="MyLoop1a" type="Sec" length="34" data="data" />"
Commented:
Dim myNewNode As System.Xml.XmlElement = doc.CreateElement("loop1a")
Dim att As System.Xml.XmlAttribute = doc.CreateAttribute("type")
att.Value = "Sec"
myNewNode.Attributes.Append(att)

You'll need to create a new attribute and append it to your element for each one that you have such as type, length, name, data, etc.

Author

Commented:
yes that worked.  had to use
 doc.DocumentElement.InsertAfter(myNewNode, nd)  instead of
doc.InsertAfter(myNewNode, nd)

dont really understand why, but it works nontheless.  thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial