Programming XML Documents

TX Text Control exposes the elements of an XML document through collections of XmlElement objects. The TextControl.GetXmlElements property returns an element collection. There is one collection for each kind of elements. In the example document above there is a collection for all Address elements and another collection for all Name elements. The following line of code gets the collection of the Name elements:

[Visual Basic]
Dim NameElements As XmlElementCollection
NameElements = TextControl1.GetXmlElements("Name")
[C#]
XmlElementCollection nameElements = textControl1.GetXmlElements("Name");

The collection object has the XmlElementCollection.GetItem method to access a single element. With the XmlElement.Text method, the following line of code displays the content of the second Name element:

[Visual Basic]
Console.WriteLine(NameElements.GetItem(2).Text)
[C#]
Console.WriteLine(nameElements.GetItem(2).Text);

The contents of elements containing sub-elements is the complete text of all sub-elements separated through new line characters (character value 10). For example the line of code:

[Visual Basic]
Console.WriteLine(TextControl1.GetXmlElements("Address").GetItem(2).Text)
[C#]
Console.WriteLine(textControl1.GetXmlElements("Address").GetItem(2).Text);

in the example above displays:

Tom Baker
Miller Street
Los Angeles

To set a new text with the Text property, the specified text string must be separated through new line characters:

[Visual Basic]
TextControl1.GetXmlElements("Address").GetItem(2).Text() _
    = "Paul Baskerville" + Chr(10) + "Jackson Street" + Chr(10) + "London"
[C#]
textControl1.GetXmlElements("Address").GetItem(2).Text
    = "Paul Baskerville\nJackson Street\nLondon";

With a For Each statement a program can iterate through an XML element collection. The following example displays all names:

[Visual Basic]
Dim NameElement As XmlElement
For Each NameElement In TextControl1.GetXmlElements("Name")
   Console.WriteLine(NameElement.Text)
Next NameElement
[C#]
foreach (XmlElement element in textControl1.GetXmlElements("Name")) {
    Console.WriteLine(element.Text);
}

This code is equivalent to the following code using the collection's Count property:

[Visual Basic]
Dim I As Integer
Dim NameElements As XmlElementCollection
NameElements = TextControl1.GetXmlElements("Name")
For I = 1 To NameElements.Count
   Console.WriteLine(NameElements.GetItem(I).Text)
Next I
[C#]
XmlElementCollection nameElements = textControl1.GetXmlElements("Name");
for (int i = 1; i <= nameElements.Count; i++) {
    Console.WriteLine(nameElements.GetItem(i).Text);
}

An XML element collection also has an Add and a Remove method to insert or delete elements. These are explained in the following section.