XMLNode.Insert

From Xojo Documentation

Method

XMLNode.Insert(NewChild as XMLNode, RefChild as XMLNode) As XMLNode

Supported for all project types and targets.

Inserts NewChild before the position of RefChild. It optionally returns a reference to the inserted node as an XMLNode.

Notes

The children being added must be children of the node/document to which they are being inserted. The example demonstrates this.

Example

The following XML is stored in a constant called kXML:

 <?xml version="1.0" encoding="UTF-8"?>
 <League>
 	<Team name="Seagulls">
 		<Player name="Bob" position="1B" />
 		<Player name="Tom" position="2B" />
 	</Team>
 	<Team name="Pigeons">
 		<Player name="Bill" position="1B" />
 		<Player name="Tim" position="2B" />
 	</Team>
 	<Team name="Crows">
 		<Player name="Ben" position="1B" />
 		<Player name="Ty" position="2B" />
 	</Team>
 </League>

To add a new team before the first team in the XML:

Var xml As New XmlDocument(kXml)

Var n1 As XmlNode = xml.DocumentElement.FirstChild

// Insert a new team before the first team currently
// in the XML
Var newTeam As XmlNode
newTeam = xml.DocumentElement.AppendChild(xml.CreateElement("Team"))
newTeam.SetAttribute("name", "Eagles")

xml.DocumentElement.Insert(newTeam, n1)

TextArea1.Value = xml.ToString