Link to home
Start Free TrialLog in
Avatar of nguyenn
nguyenn

asked on

Insert a child node into a XML document

I have a XML document with formated:

<MyList>
 <MyGroup>
  <GroupID>1</GroupID>
  <GroupName>Name 1</GroupName>
 </MyGroup>
 <MyGroup>
  <GroupID>1</GroupID>
  <GroupName>Name 2</GroupName>
 </MyGroup>
 <MyGroup>
  <GroupID>2</GroupID>
  <GroupName>Name 4</GroupName>
 </MyGroup>
</MyList>

Suppose I have a new node(GroupID = 1, GroupName = Name 5). How could I insert the new node into the XML doc, at the end of nodes have GroupID = 1 (and ofcourse, before the node has GroupID = 2)

Thanks in advance
nguyenn
ASKER CERTIFIED SOLUTION
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Let's try again:

Private Sub Command1_Click()
Dim xmldoc As MSXML2.DOMDocument

' Load the XML document
Set xmldoc = New MSXML2.DOMDocument
xmldoc.Load "c:\temp\temp.xml"

AddNode xmldoc, "1", "Name 5"
Debug.Print xmldoc.xml

AddNode xmldoc, "3", "Name 6"
Debug.Print xmldoc.xml

Set xmldoc = Nothing

End Sub

Sub AddNode(xmldoc As MSXML2.DOMDocument, ByVal GroupID As String, ByVal GroupName As String)
Dim xmlNewNode As MSXML2.IXMLDOMNode
Dim xmlNode As MSXML2.IXMLDOMNode
Dim Done As Boolean

' Create the node
Set xmlNewNode = xmldoc.createNode(NODE_ELEMENT, "MyGroup", vbNullString)
Set xmlNode = xmlNewNode.appendChild(xmldoc.createNode(NODE_ELEMENT, "GroupID", vbNullString))
xmlNode.Text = GroupID
Set xmlNode = xmlNewNode.appendChild(xmldoc.createNode(NODE_ELEMENT, "GroupName", vbNullString))
xmlNode.Text = GroupName

' Find the node to insert
Set xmlNode = xmldoc.selectSingleNode("/MyList/MyGroup")
Done = False
Do While Not xmlNode Is Nothing And Not Done
   If CLng(xmlNode.childNodes(0).Text) > CLng(GroupID) Then
      Done = True
   Else
      Set xmlNode = xmlNode.nextSibling
   End If
Loop
xmldoc.documentElement.insertBefore xmlNewNode, xmlNode

End Sub
Avatar of nguyenn
nguyenn

ASKER

Thanks for your excellent codes, Acperkins. You help me solve out the problem

I very appreciate your help, and have a nice day :)
nguyenn