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:

[C#]
XmlElementCollection nameElements = textControl1.GetXmlElements("Name");
[Visual Basic]
Dim NameElements As 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:

[C#]
Console.WriteLine(nameElements.GetItem(2).Text);
[Visual Basic]
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:

[C#]
Console.WriteLine(textControl1.GetXmlElements("Address").GetItem(2).Text);
[Visual Basic]
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:

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

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

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

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

[C#]
XmlElementCollection nameElements = textControl1.GetXmlElements("Name");
for (int i = 1; i <= nameElements.Count; i++) {
    Console.WriteLine(nameElements.GetItem(i).Text);
}
[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

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

<< Previous Next >>