Inserting and Deleting XML Elements

Technical Articles > Working with XML Files

The structure of an XML document is described through a document type description (DTD) either contained inline in the XML file or in a separate DTD file. The following is an example of a DTD file belonging to the XML example above (addresses.dtd):

<!ELEMENT Addresses (DocumentHeadline, AddressTable)>
<!ELEMENT DocumentHeadline (#PCDATA)>
<!ELEMENT AddressTable (Address+)>
<!ELEMENT Address (Name, Street, City)>

The DTD allows text only for elements with the #PCDATA statement. Furthermore, the document must have a single document headline and a single address table. The address table can have one or more addresses and each address must have three sub-elements: Name Street and City.

With all of these instructions, inserting or removing elements is allowed only for complete addresses. Inserting or removing one of the other elements results in an invalid document and an XMLInvalid event occurs if a program tries it.

To insert an address first create a new XMLElement object, initialize it with text and then use the Address collection's Add method:

Dim NewAddress As Object
Set NewAddress = CreateObject("TIS.TX.XMLElement.26)
NewAddress.Text = "Paul Baskerville" & Chr(10) & "Jackson Street" & Chr(10) & "London"
TXTextControl1.XMLElements("Address").Add NewAddress, , 2

This code inserts the new address after the second address in the document. Using the Add method's before parameter an element can also be inserted before a certain element.

The following line of code removes the address just inserted:


Because the DTD enforces at least one address, trying to remove the last address also results in an invalid document and an XMLInvalid event occurs.