Oct
12
Written by:
Steve Gray
10/12/2010 3:14 PM
InsertAfter gave me fits today. This code:
Sub test2()
Try
'The reference node is not a child of this node
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml("<root><doc><node1>1</node1><node3/></doc></root>")
Dim xnNode1 As XmlNode = xmlDoc.SelectSingleNode("root/doc/node1")
Dim xnNode2 As XmlNode = xmlDoc.CreateElement("node2")
xnNode2.InnerXml = "steve"
xmlDoc.InsertAfter(xnNode2, xnNode1)
MsgBox(xmlDoc.ToString)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Always returns ‘The reference node is not a child of this node’. Grrr.
This technique works, though:
Sub test()
Try
'The reference node is not a child of this node
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml("<root><doc><node1>1</node1><node3/></doc></root>")
Dim xnNode1 As XmlNode = xmlDoc.SelectSingleNode("root/doc/node1")
Dim xnParent As XmlNode = xnNode1.ParentNode
Dim xnNode2 As XmlNode = xmlDoc.CreateElement("node2")
xnNode2.InnerXml = "steve"
xnParent.InsertAfter(xnNode2, xnNode1)
MsgBox(xmlDoc.ToString)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
As always, I welcome your comments!