Modifying XML Files in WSH - Placing new elements
(Page 3 of 4 )
The previous example demonstrates the simplest approach to adding new records by appending them as children to the existing document tree. Sometimes, however, you may find that you don't want your newly created element to appear as the last element on the tree. For example, perhaps you wish for it to be the first element.
Set objTrackList = objXmlDoc.selectSingleNode("/playlist/trackList")
Set objFirstChild = objTrackList.firstChild
In this example, I'm taking a slightly different approach. The selectSingleNode method returns a reference to the trackList element. That reference exposes a firstChild method that returns a reference to the object's first child object. In our case, this is the first track element.
Set objTrack = objXmlDoc.createElement("track")
objTrackList.insertBefore objTrack, objFirstChild
Now, we can create a new track element and place it in the document as the first child. To do so, we'll need to use the insertBefore method of the trackList object. It accepts two parameters: the first is an object reference to the element to be inserted into the document tree and the second is an object reference to the element before which it should be inserted. In this case, the insertBefore method is inserting the newly created track element as a sibling immediately before the first existing track element.
There are several other methods available that can be used to place newly created elements into the document tree as well.
The firstChild method has a counterpart lastChild method. The lastChild method will return a reference to the last child element for an object.
Along with the firstChild and lastChild method, you can also find references to other elements using the previousSibling and nextSibling methods. Just as their names imply, these methods return references to the elements immediately preceding and following an object, respectively. These methods can often be used in conjunction to create the desired affect.
Set objTrackList = objXmlDoc.selectSingleNode("/playlist/trackList")
Set objFirstChild = objTrackList.firstChild
Set objSecondChild = objFirstChild.nextSibling
Set objTrack = objXmlDoc.createElement("track")
objTrackList.insertBefore objTrack, objSecondChild
This example will insert the newly created element as the second record. It first uses the firstChild method to return a reference to the first track element. Then, the nextSibling method is used to return a reference to the second track element. Finally, the insertBefore method is used to insert the newly created track element before the second existing one, thus making the new element the second element.
Next: Modifying and deleting existing records >>
More Windows Scripting Articles
More By Nilpo