Modifying XML Files in WSH - Adding new elements
(Page 2 of 4 )
In order to add a new element, we must first create a reference to the new element's parent object. This is most easily done by using a query string. In this case, we need to add a new track element. If you examine the XML file, you will see that track elements are children of the trackList element.
Set objTrackList = objXmlDoc.selectSingleNode("/playlist/trackList")
The selectSingleNode method is used to return a single node based upon the query string provided. In this case, it returns a reference to the trackList element.
Set objTrack = objXmlDoc.createElement("track")
objTrackList.appendChild objTrack
Next, you can use the XML Document object's createElement method to create a new track element. It is then attached to the document as a child of the trackList node by using the appendChild method exposed by that object.
Set objLocation = objXmlDoc.createElement("location")
objLocation.Text = "http://www.nilpo.com/pub/tracks/Crossfade%20-%20Cold.mp3"
objTrack.appendChild objLocation
Set objTitle = objXmlDoc.createElement("title")
objTitle.Text = "Dead Skin"
objTrack.appendChild objTitle
Set objCreator = objXmlDoc.createElement("creator")
objCreator.Text = "Crossfade"
objTrack.appendChild objCreator
Set objInfo = objXmlDoc.createElement("info")
objInfo.Text = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/" _
& "viewAlbum?i=187470715%38id=187470617%38s=143441"
objTrack.appendChild objInfo
Set objAlbum = objXmlDoc.createElement("album")
objAlbum.Text = "Crossfade"
objTrack.appendChild objAlbum
Set objTrackNum = objXmlDoc.createElement("trackNum")
objTrackNum.Text = "2"
objTrack.appendChild objTrackNum
Each of the property elements can then be added to the newly created track element in the same manner. The text property of each newly created child element is set using the text property.
objXmlDoc.save "C:Playlist.xml"
Once you've added all of the required elements, a call to the XML Document object's save method will write those changes to the XML file.
Next: Placing new elements >>
More Windows Scripting Articles
More By Nilpo