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
<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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
I very appreciate your help, and have a nice day :)
nguyenn
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_ELE
Set xmlNode = xmlNewNode.appendChild(xml
xmlNode.Text = GroupID
Set xmlNode = xmlNewNode.appendChild(xml
xmlNode.Text = GroupName
' Find the node to insert
Set xmlNode = xmldoc.selectSingleNode("/
Done = False
Do While Not xmlNode Is Nothing And Not Done
If CLng(xmlNode.childNodes(0)
Done = True
Else
Set xmlNode = xmlNode.nextSibling
End If
Loop
xmldoc.documentElement.ins
End Sub