Hi, Ed. Thanks for the response.
I saw that example but I can't use the FirstChild property because, as the
XML doc grows (and it will grow), FirstChild may not be the place where I
want to insert an element.
I need to be able to insert an element anywhere in a document.
Any other suggestions?
Thanks again,
Mike
"Gomolyako Eduard" <ed**************@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
mike ?????(?):
I meant to say "I want to add a new element "before" Element1.
"mike" <mi***@slomins.com> wrote in message
news:uQ**************@tk2msftngp13.phx.gbl... Hello.
Let's say I have the following XML document:
<ROOT><Element1>Some Text</Element1></ROOT>
I want to add a new element after Element1. I tried the following but,
naturally, it doesn't work:
Dim oElem as XmlElement
Dim oNode as XmlNode
Dim oRoot as XmlNode
Dim oDoc as New XmlDocument
oDoc.LoadXML("<ROOT><Element1>Some Text</Element1></ROOT>")
oRoot = oDoc.DocumentElement
oNode = oRoot.SelectSingleNode("//ROOT/Element1")
oElem = oDoc.CreateElement("InsertMe")
oElem.InnerText = "A New Element"
oRoot.InsertBefore(oElem, oNode) <----- This is the error
The error I get is: "The reference node is not a child of this node."
How do I go about inserting the new element at a specific point?
Thanks in advance,
Mike
MSDN Library - XmlNode class InsertBefore method example:
Option Strict
Option Explicit
Imports System
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim doc As New XmlDocument()
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" & _
"<title>Pride And Prejudice</title>" & _
"</book>")
Dim root As XmlNode = doc.DocumentElement
'Create a new node.
Dim elem As XmlElement = doc.CreateElement("price")
elem.InnerText = "19.95"
'Add the node to the document.
root.InsertBefore(elem, root.FirstChild)
Console.WriteLine("Display the modified XML...")
doc.Save(Console.Out)
End Sub 'Main
End Class 'Sample
I hope this helps you.
Best, Ed.