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)> <!ELEMENT Name (#PCDATA)> <!ELEMENT Street (#PCDATA)> <!ELEMENT City (#PCDATA)>
A DTD allows text only for elements with the #PCDATA statement. Furthermore, this DTD defines that 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. Should a program try to insert or remove one of the other elements, an invalid document and an XmlInvalid event occurs.
To insert an address, first create a new XmlElement object, initialize it with a name and a text and then use the Address collection's Add method as shown in the following piece of code:
[C#] XmlElement newAddress = new XmlElement("Address", "Paul Baskerville\nJackson Street\nLondon"); textControl1.GetXmlElements("Address").Add(newAddress, -1, 2);
[Visual Basic] Dim NewAddress As New XmlElement("Address", _ "Paul Baskerville" + Chr(10) + "Jackson Street" + Chr(10) + "London") TextControl1.GetXmlElements("Address").Add(NewAddress, -1, 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:
[Visual Basic] TextControl1.GetXmlElements("Address").Remove(3)
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.