XML as a Data Description and Distribution Language

spongereasonInternet και Εφαρμογές Web

12 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

81 εμφανίσεις






















XML as a Data Description and Distribution Language


Class Notes and Examples

















Ted Faison

S
oftware Development 2000 Conference

San Jose, California

2000
-
3
-
23









Table of Contents








Example 1


Ac
cessing the XML DOM using Java

................................
.......

1

Example 2


Locating elements in an XML DOM using Delphi

...................

2

Example 3


XML
-
Data Characters and Strings

................................
..........

9

Example 4


XML
-
Data Boo
leans

................................
.............................

10

Example 5


XML
-
Data Numbers

................................
..............................

11

Example 6


XML
-
Data Date and Time
................................
.....................

14

Example 7

Accessing Datatypes in JavaScript

................................
...........

15

Examp
le 8

Accessing Datatypes in Visual Basic

................................
.......

17

Example 9

Accessing Datatypes in Visual C++

................................
.........

19

Example 10


Aggregate Data Structures using Delphi

...............................

25

Example 11


Model
ing a Structured object in XML

................................
..

35

Example 12


Saving an ADO recordset in XML

................................
........

37


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
1

of



Example 1



Accessing the XML DOM using Java

Referenced on slide 4


This code sample shows how to use the public
domain
Xerces
-
J
xml parser from the
Apache Software Foundation to access elements in the xmldom tree. The full Java
package, with source code and examples can be downloaded from
http://xml.apache.org/
.



package Acces
singTypedData;

1


2

import java.lang.*;

3

import ...

4

import org.apache.xerces.*;

5

import org.apache.xerces.parsers.*;

6


7

public class Frame1 extends JFrame {

8



9


// ...

10


11


void jButton1_actionPerformed(ActionEvent e) {

12


13


org.apache.xerces.parsers.DOMParser parse
r;

14


15


parser = new DOMParser();

16


try {

17


parser.setValidating(true);

18


parser.parse("ExampleSimple.xml");

19


} catch (Exception exception) {

20


System.err.println(exception);

21


}

22


23


// access the elements in the xmldom tree

24


25


org.w3c.dom.Document roo
tNode = parser.getDocument();

26


if (rootNode == null) {

27


System.out.println("No root node element found.");

28


return;

29


}

30


31


org.w3c.dom.Node employee = rootNode.getChildNodes().item(0);

32


org.w3c.dom.NodeList children = employee.getChildNodes();

33


if

(children != null) {

34


System.out.println("The node " + employee.getNodeName() +

35


" has " + children.getLength() +

36


" children.");

37


int len = children.getLength();

38


for ( int i = 0; i < len; i++
)

39


// do something with the child nodes

40


System.out.println(children.item(i).getNodeName() );

41


}

42

}

43

}

44


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
2

of



Example 2


Locating elements in an XML DOM using
Delphi

Referenced on slide 5


This code sample shows how to use the Microsoft
msxml

parse
r to access elements in the
xmldom tree using Borland Delphi. The sample is a small application that loads an xml
document, as shown in Figure 1.



Figure
1

-

The xml tree of the loaded document.


Clicking the
Run Query

button run
s the selected query on the xml data and displays the
result tree in the
Query Result

tab, as shown in Figure 2.



Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
3

of





Figure
2

-

The queried results, displayed as a tree.


The code in the following file creates the form. The event h
andler
ButtonRunQueryClick

selects a query string and extracts the requested data from the
xml file.



unit Main;

1


2

interface

3


4

uses

5


Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,

6


Dialogs, StdCtrls, OleCtrls, SHDocVw, ExtCtrls, MSXML2_
TLB, ComCtrls;

7


8

type

9


TFMMain = class(TForm)

10


Panel1: TPanel;

11


ButtonRunQuery: TButton;

12


Panel2: TPanel;

13


PageControl1: TPageControl;

14


TabSheet1: TTabSheet;

15


TabSheet2: TTabSheet;

16


Label2: TLabel;

17


WebBrowserXMLData: TWebBrowser;

18



Label3: TLabel;

19


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
4

of




WebBrowserQueryResult: TWebBrowser;

20


GroupBox1: TGroupBox;

21


EditQueryPattern: TEdit;

22


RadioButtonAutobiographies: TRadioButton;

23


RadioButtonPhilosophy: TRadioButton;

24


RadioButtonLessThan10Dollars: TRadioButton;

25


Rad
ioButtonCustomSearch: TRadioButton;

26


procedure ButtonRunQueryClick(Sender: TObject);

27


procedure FormCreate(Sender: TObject);

28


procedure FormDestroy(Sender: TObject);

29


function QueryPattern: String;

30


public

31


XmlDoc: IXMLDOMDocument;

32


Stri
ngCollection: TStringList;

33


end;

34


35

var

36


FMMain: TFMMain;

37


38

implementation

39


40

uses DisplayXML;

41


42

{$R *.DFM}

43


44

function TFMMain.QueryPattern: String;

45

begin

46


Result := '';

47


if RadioButtonAutobiographies.Checked then

48


Result := '/bookstore/book[@genre="autobi
ography"]'

49


else if RadioButtonPhilosophy.Checked then

50


Result := '/bookstore/book[@genre="philosophy"]'

51


else if RadioButtonLessThan10Dollars.Checked then

52


Result := '/bookstore/book [price $lt$ 9]'

53


else

54


Result := EditQueryPattern.Text;

55

end;

56


57

procedure TFMMain.ButtonRunQueryClick(Sender: TObject);

58

var

59


Flags: OLEVariant;

60


NodeList: IXMLDOMNodeList;

61

begin

62


NodeList := XmlDoc.documentElement.selectNodes(QueryPattern);

63


StringCollection.Clear;

64


HTMLforNodeList(StringCollection, NodeList);

65



StringCollection.SaveToFile('c:
\
temp.htm');

66


Flags := 0;

67


WebBrowserQueryResult.Navigate(WideString('c:/temp.htm'),

68


Flags, Flags, Flags, Flags);

69

end;

70


71

procedure TFMMain.FormCreate(Sender: TObject);

72

var

73


Flags: OLEVaria
nt;

74

begin

75


XmlDoc := CoDOMDocument.Create;

76


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
5

of




XmlDoc.async := False;

77


XmlDoc.load('sample.xml');

78


79


StringCollection := TStringList.Create;

80


HTMLforNode(StringCollection, XmlDoc.documentElement);

81


StringCollection.SaveToFile('c:
\
temp.htm');

82


Flags := 0
;

83


WebBrowserXMLData.Navigate(WideString('c:/temp.htm'),

84


Flags, Flags, Flags, Flags);

85

end;

86


87

procedure TFMMain.FormDestroy(Sender: TObject);

88

begin

89


XmlDoc := nil;

90


StringCollection.Free;

91

end;

92


93

end.

94


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
6

of



1

The code in this file ta
kes an xml tree and turns it into an HTML document with
indentation and color coding.


unit DisplayXML;

1


2

interface

3


4

uses

5


Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,

6


Dialogs, StdCtrls, MSXML2_TLB;

7


8


procedure HTMLforNode(TheHTMLTe
xt: TStrings;

9


TheXmlNode: IXMLDOMNode);

10


procedure HTMLforNodeList(TheHTMLText: TStrings;

11


TheXmlNodeList: IXMLDOMNodeList);

12


procedure DumpTree(TheNode: IXMLDOMNode; TheHTMLText: TStrings);

13


14

implement
ation

15


16

// this code is loosely based on the Microsoft JavaScript example at

17

//
http://msdn.microsoft.com/downloads/samples/internet/xml/tree_viewer/default.asp

18


19

procedure ProcessAttributes(TheNode: IXMLDOMNode;

20


TheHTMLText: TSt
rings);

21

var

22


I, L: Integer;

23


A: IXMLDOMNode;

24

begin

25


if TheNode.attributes.length = 0 then Exit;

26


L := TheNode.attributes.length;

27


for I := 0 to L
-
1 do

28


begin

29


A := TheNode.attributes.item [I];

30


TheHTMLText.Add('<span class=attr> ' +

31



a.nodeName +

32


'="' +

33


a.text + '"</span>');

34


end;

35

end;

36


37

function IsMixedNode(TheNode: IXMLDOMNode): Boolean;

38

var

39


I: Integer;

40


Child: IXMLDOMNode;

41

begin

42


Result := True;

43


for I := 0 to TheNode.childNode
s.length
-
1 do

44


begin

45


Child := TheNode.childNodes.item [I];

46


if (child.nodeTypeString = 'text') or

47


(child.nodeTypeString = 'cdata_section') or

48


(child.nodeTypeString = 'entity_reference') then

49


Exit;

50


end;

51


Result := False;

52


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
7

of



end;

53


54

procedure ProcessChildren(TheNode: IXMLDOMNode; TheHTMLText: TStrings);

55

var

56


I, Num: Integer;

57

begin

58


if TheNode.childNodes <> nil then

59


Num := TheNode.childNodes.length

60


else

61


Num := 0;

62


63


// close the element tag (if empty, use shorthand)

64


65


if
Num = 0 then // tag is empty

66


TheHTMLText.Add('<span class=tag>/&gt;</span>')

67


else

68


TheHTMLText.Add('<span class=tag>&gt;</span>');

69


70


// process the children of the element if it has any

71


if Num > 0 then // tag has children

72


begin

73


i
f IsMixedNode(TheNode) then

74


TheHTMLText.Add(TheNode.text)

75


else

76


for I := 0 to Num
-
1 do

77


DumpTree(TheNode.childNodes.item [I], TheHTMLText);

78


TheHTMLText.Add('<span class=tag>&lt;/' +

79


TheNode.nodeName +

80



'&gt;</span>');

81


end;

82

end;

83


84

// Format the XML into HTML

85

procedure DumpTree(TheNode: IXMLDOMNode; TheHTMLText: TStrings);

86

begin

87


if TheNode = nil then

88


begin

89


TheHTMLText.Add('<DL class=xml><DD>');

90


TheHTMLText.Add('</DD></DL>');

91


Ex
it;

92


end;

93


94


if TheNode.nodeTypeString = 'comment' then

95


begin

96


TheHTMLText.Add('<DL class=xml><DD>');

97


TheHTMLText.Add('<span class=comment>&lt;!
--
' +

98


TheNode.text +

99


'
--
&gt;</span>' +

100


'</DD></DL>');

101


TheHTMLText.Add('</DD></DL>');

102


TheHTMLText.Add('</DD></DL>');

103


Exit;

104


end;

105


106


TheHTMLText.Add('<DL class=xml><DD>');

107


TheHTMLText.Add('<span class=tag>&lt;' +

108


TheNode.nodeName +

109


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
8

of




'</span>');

110



ProcessAttributes(TheNode, TheHTMLText);

111


ProcessChildren(TheNode, TheHTMLText);

112


TheHTMLText.Add('</DD></DL>');

113

end;

114


115

procedure AddStyleSheet(TheHTMLText: TStrings);

116

begin

117


TheHTMLText.Add('<STYLE TYPE="text/css">');

118


TheHTMLText.Add('.xml {font
-
weig
ht: bold}');

119


TheHTMLText.Add('.tag {color: green}');

120


TheHTMLText.Add('</STYLE>');

121

end;

122


123

procedure HTMLforNode(TheHTMLText: TStrings; TheXmlNode: IXMLDOMNode);

124

begin

125


TheHTMLText.Add('<HTML>');

126


AddStyleSheet(TheHTMLText);

127


DumpTree(TheXmlNode, TheHT
MLText);

128


TheHTMLText.Add('</HTML>');

129

end;

130


131

procedure HTMLforNodeList(TheHTMLText: TStrings;

132


TheXmlNodeList: IXMLDOMNodeList);

133

var

134


I: Integer;

135

begin

136


TheHTMLText.Add('<HTML>');

137


AddStyleSheet(TheHTMLText);

138


for I := 0 to Th
eXmlNodeList.length
-
1 do

139


DumpTree(TheXmlNodeList.item [I], TheHTMLText);

140


TheHTMLText.Add('</HTML>');

141

end;

142


143

end.

144


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠
9

of



Example 3


XML
-
Data Characters and Strings

Referenced on slide 11



Schema, in the file named
Schema
-
Strings.xml



<?xml version="1.0
"?>

1


2

<Schema xmlns="urn:schemas
-
microsoft
-
com:xml
-
data"

3


xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

4



5


<ElementType name='MyChar' content='textOnly'

6


dt:type='char'/>

7



8


<ElementType name='MyString' content='tex
tOnly'

9


dt:type='string'

10


dt:minLength='5'

11


dt:maxLength='20'/>

12


13

</Schema>

14



XML document referencing the schema in
Schema
-
Strings.xml



<?xml version="1.0"?>

15


16

<StringTest>

17


18


<MyChar xmlns="x
-
schema:Schema
-
Stri
ngs.xml">

19


a

20


</MyChar>

21



22


<MyString xmlns="x
-
schema:Schema
-
Strings.xml">

23


asdfk23479

24


</MyString>

25



26

</StringTest>

27


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example 4


XML
-
Data Booleans

Referenced on slide 12


Schema, in the file named
Schema
-
Boolean.xml



<?xml version="1.0"?>

1


2

<S
chema xmlns="urn:schemas
-
microsoft
-
com:xml
-
data"

3


xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

4


5


<ElementType name='Boolean' content='textOnly' dt:type='boolean'/>

6


7

</Schema>

8



XML document referencing the schema in
Schema
-
Boolean.xml



<?xml

version="1.0"?>

9


10

<Boolean xmlns="x
-
schema:Schema
-
Boolean.xml">

11

1

12

</Boolean>

13


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example 5


XML
-
Data Numbers

Referenced on slides 13
-
17


Schema, in the file named
SchemaNumbers.xml



<?xml version="1.0"?>

1


2

<Schema xmlns="urn:schemas
-
microsoft
-
com:xml
-
data
"

3


xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

4


5


<ElementType name='MyNumber' content='textOnly'

6


dt:type='number'/>

7


<ElementType name='MyInteger' content='textOnly'

8


dt:type='int'/>

9


<ElementType name='My
Byte' content='textOnly'

10


dt:type='i1'/>

11


<ElementType name='MyWord' content='textOnly'

12


dt:type='i2'/>

13


<ElementType name='MyLong' content='textOnly'

14


dt:type='i4'/>

15


<ElementType name='MyExtendedLong'

content='textOnly'

16


dt:type='i8'/>

17


<ElementType name='MyUnsignedByte' content='textOnly'

18


dt:type='ui1'/>

19


<ElementType name='MyUnsignedWord' content='textOnly'

20


dt:type='ui2'/>

21


<ElementType name='My
UnsignedLong' content='textOnly'

22


dt:type='ui4'/>

23


<ElementType name='MyUnsignedExtendedLong' content='textOnly'

24


dt:type='ui8'/>

25


<ElementType name='MyFixed' content='textOnly'

26


dt:type='fixed.14.4'/>

27



<ElementType name='MyFloat' content='textOnly'

28


dt:type='r4'/>

29


<ElementType name='MyDouble' content='textOnly'

30


dt:type='r8'/>

31


<ElementType name='MyHexadecimal' content='textOnly'

32


dt:type='bin.hex'/>

33


<ElementType name='MyBinary64' content='textOnly'

34


dt:type='bin.base64'/>

35

</Schema>

36


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



XML document referencing the schema in
SchemaNumbers.xml



<?xml version="1.0"?>

1


2

<NumberTest>

3



4


<MyNumber xmlns="x
-
schema:SchemaNumbers.xml">

5


-
100.2467

6


</MyNumber>

7



8


<MyInteger xmlns="x
-
schema:SchemaNumbers.xml">

9


-
100356

10


</MyInteger>

11



12


<MyByte xmlns="x
-
schema:SchemaNumbers.xml">

13


-
23

14


</MyByte>

15



16


<MyWord xmlns="x
-
schema:SchemaNumbers.xml">

17


20123

18


</MyWord>

19



20


<MyLong x
mlns="x
-
schema:SchemaNumbers.xml">

21


-
222555333

22


</MyLong>

23



24


<MyExtendedLong xmlns="x
-
schema:SchemaNumbers.xml">

25


-
222555333000

26


</MyExtendedLong>

27



28


<MyUnsignedByte xmlns="x
-
schema:SchemaNumbers.xml">

29


200

30


</MyUnsignedByte>

31



32


<MyUnsign
edWord xmlns="x
-
schema:SchemaNumbers.xml">

33


40555

34


</MyUnsignedWord>

35



36


<MyUnsignedLong xmlns="x
-
schema:SchemaNumbers.xml">

37


3100200300

38


</MyUnsignedLong>

39



40


<MyUnsignedExtendedLong xmlns="x
-
schema:SchemaNumbers.xml">

41


3100200300222

42


</MyUn
signedExtendedLong>

43



44


<MyFixed xmlns="x
-
schema:SchemaNumbers.xml">

45


-
100.2467

46


</MyFixed>

47



48


<MyFloat xmlns="x
-
schema:SchemaNumbers.xml">

49


300.344

50


</MyFloat>

51



52



53


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




<MyFloat xmlns="x
-
schema:SchemaNumbers.xml">

54


3E
-
20

55


</MyFloat>

56



57


<My
Double xmlns="x
-
schema:SchemaNumbers.xml">

58


2.345345345

59


</MyDouble>

60


61


<MyHexadecimal xmlns="x
-
schema:SchemaNumbers.xml">

62


104FED

63


</MyHexadecimal>

64


65


<MyBinary64 xmlns="x
-
schema:SchemaNumbers.xml">

66


89s3G

67


</MyBinary64>

68


69

</NumberTest>
70


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example

6


XML
-
Data Date and Time

Referenced on slides 18
-
19


Schema, in the file named
SchemaDateTimes.xml



<?xml version="1.0"?>

1


2

<Schema xmlns="urn:schemas
-
microsoft
-
com:xml
-
data"

3


xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

4



5


<ElementType
name='MyDate' content='textOnly'

6


dt:type='date'/>

7



8


<ElementType name='MyTime' content='textOnly'

9


dt:type='time'/>

10



11


<ElementType name='MyDateTime' content='textOnly'

12


dt:type='
datetime'/>

13


14

</Schema>
15



XML document referencing the schema in
SchemaDateTimes.xml



<?xml version="1.0"?>

16


17

<DateTimeTest>

18


19


<MyDate xmlns="x
-
schema:SchemaDateTimes.xml">

20


2000
-
01
-
13

21


</MyDate>

22



23


<MyTime xmlns="x
-
schema:SchemaDateTimes.xml">

24


19:02:44.030

25


</MyTime>

26



27


<MyDateTime xmlns="x
-
schema:SchemaDateTimes.xml">

28


2000
-
01
-
13T19:02:44.030

29


</MyDateTime>

30



31


<MyDateTime xmlns="x
-
schema:SchemaDateTimes.xml">

32


2000
-
01
-
13T19:02:44.030

33


</MyDateTime>

34



35


<MyDateTime xmlns="x
-
schema:
SchemaDateTimes.xml">

36


2000
-
01
-
13

37


</MyDateTime>

38



39

</DateTimeTest>
40


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




Example 7

Accessing Datatypes in JavaScript

Referenced on slide 25


This example parses the elements in a simple xml file containing the elements:


<Employee xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

1


2


<FirstName dt:dt="string"> Fred </FirstName>

3


<LastName dt:dt="string"> Smith </LastName>

4


<IsMarried dt:dt="boolean"> 1 </IsMarried>

5


<SpouseName dt:dt="string"> Helen </SpouseName>

6


<Age dt:dt="int"> 34 </Age>

7


<Salary d
t:dt="int"> 56000 </Salary>

8


<PercentLastRaise dt:dt="float"> 7.5 </PercentLastRaise>

9



10

</Employee>

11


The script displays the value of each element in the message box in Figure 3.




Figure
3

-

The message box displayed by the J
avaScript example.




Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



JavaScript Code



<HTML>

1

<SCRIPT Language="JavaScript">

2


3


var parser;

4


var employee, firstName, lastName, isMarried;

5


var spouseName, age, salary, percentLastRaise;

6


7


parser = new ActiveXObject("Microsoft.XMLDOM");

8


parser.async

= false;

9


parser.validateOnParse = true;

10


parser.load("ExampleSimple.xml");

11


if (parser.parseError != 0)

12


alert(parser.parseError.reason);

13



14


// access the elements in the xmldom tree

15


16

//************************************************************
*****

17

// use [nodeTypedValue] property to get typed values *

18

// use [text] property to get Variant values *

19

// e.g. *

20

// isMarried = employee.childNodes.item(2).te
xt; *

21

// isMarried = employee.childNodes.item(2).nodeTypedValue; *

22

//*****************************************************************

23


24


employee = parser.documentElement;

25


firstName = employee.childNodes.item(0).tex
t;

26


lastName = employee.childNodes.item(1).text;

27


isMarried = employee.childNodes.item(2).text;

28


spouseName = employee.childNodes.item(3).text;

29


age = employee.childNodes.item(4).text;

30


salary = employee.chi
ldNodes.item(5).text;

31


percentLastRaise = employee.childNodes.item(6).text;

32


33


var NoYes = ['No', 'Yes'];

34



35


alert("Employee information
\
n
\
n" +

36


"First Name:
\
t" + firstName + "
\
n" +

37


"Last Name:
\
t" + lastName + "
\
n" +

38


"Married
:
\
t
\
t" + NoYes [isMarried] + "
\
n" +

39


"Spouse Name:
\
t" + spouseName + "
\
n" +

40


"Age:
\
t
\
t" + age + "
\
n" +

41


"Salary:
\
t
\
t" + salary + "
\
n" +

42


"Last Raise:
\
t" + percentLastRaise + " %
\
n
\
n");

43



44


45

</SCRIPT>

46

</HTML>
47


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Ex
ample 8

Accessing Datatypes in Visual Basic

Referenced on slide 25


This example parses the elements in the file used in the previous example, shown here
again for convenience:


<Employee xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

1


2


<FirstName dt:
dt="string"> Fred </FirstName>

3


<LastName dt:dt="string"> Smith </LastName>

4


<IsMarried dt:dt="boolean"> 1 </IsMarried>

5


<SpouseName dt:dt="string"> Helen </SpouseName>

6


<Age dt:dt="int"> 34 </Age>

7


<Salary dt:dt="int"> 56000 </Salary>

8


<PercentLastR
aise dt:dt="float"> 7.5 </PercentLastRaise>

9



10

</Employee>
11



The script displays the value of each element in the message box in Figure 4.




Figure
4

-

The message box displayed by the Visual Basic example.




Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Visual Basic Code



< Private Sub Command1_Click()

1


2


Dim parser As MSXML2.DOMDocument

3


Dim employee

4


Dim firstName, lastName, spouseName As String

5


Dim isMarried As Boolean

6


Dim age As Integer

7


Dim salary, percentLastRaise As Double

8



9


Set parser = New DOMDocument

10



parser.async = False

11


parser.validateOnParse = True

12


If parser.Load("ExampleSimple.xml") = False Then

13


MsgBox "Error loading the XML file"

14


End If

15


If parser.parseError <> 0 Then

16


MsgBox (parser.parseError.reason)

17


End If

18



19

' access the elemen
ts in the xmldom tree

20


21


Set employee = parser.documentElement

22


firstName = employee.childNodes.Item(0).nodeTypedValue

23


lastName = employee.childNodes.Item(1).nodeTypedValue

24


isMarried = employee.childNodes.Item(2).nodeTypedValue

25


spouseName = employee
.childNodes.Item(3).nodeTypedValue

26


age = employee.childNodes.Item(4).nodeTypedValue

27


salary = employee.childNodes.Item(5).nodeTypedValue

28


percentLastRaise = employee.childNodes.Item(6).nodeTypedValue

29


30

' use the typed variables...

31


If age < 65 Then

32



MsgBox (firstName + lastName + "still has" + Str(65
-

age) +

33


" years before retiring.")

34


End If

35



36

' to use the variables as strings, we have to convert them explicitly

37


MsgBox ("Employee information" + vbCrLf + vbCrLf + _

38


"Firs
t Name:" + vbTab + firstName + vbCrLf + _

39


"Last Name:" + vbTab + lastName + vbCrLf + _

40


"Married:" + vbTab + vbTab + " " +

41


Format(isMarried) + vbCrLf + _

42


"Spouse Name:" + vbTab + spouseName + vbCrLf + _

43



"Age:" + vbTab + vbTab + " " + Format(age) + vbCrLf + _

44


"Salary:" + vbTab + vbTab + " " + Format(salary) + vbCrLf + _

45


"Last Raise:" + vbTab + " " +

46


Format(percentLastRaise) + " %" + vbCrLf)

47


48

End Sub
49


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Exampl
e 9

Accessing Datatypes in Visual C++

Referenced on slide 25


This example parses the elements in the file used in the previous example, shown here
again for convenience:


<Employee xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

1


2


<FirstName dt:dt="st
ring"> Fred </FirstName>

3


<LastName dt:dt="string"> Smith </LastName>

4


<IsMarried dt:dt="boolean"> 1 </IsMarried>

5


<SpouseName dt:dt="string"> Helen </SpouseName>

6


<Age dt:dt="int"> 34 </Age>

7


<Salary dt:dt="int"> 56000 </Salary>

8


<PercentLastRaise d
t:dt="float"> 7.5 </PercentLastRaise>

9



10

</Employee>

11


The script displays the value of each element in the message box in Figure 5.



Figure
5

-

The message box displayed by the Visual C++ example.



Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Visual C++Code


This example
is based on sample code available at:

http://msdn.microsoft.com/xml/c
-
frame.htm?948336454690#/xml/xmlguide/default.asp



// ExampleDlg.cpp : implementation file

1

//

2


3

#include "stdafx.h"

4

#include "Example.h"

5

#include "ExampleDlg.h"

6


7

#ifdef _DEBUG

8

#define ne
w DEBUG_NEW

9

#undef THIS_FILE

10

static char THIS_FILE[] = __FILE__;

11

#endif

12


13

///////////////////////////////////////////////////////////////////////
14

//////

15

// CExampleDlg dialog

16


17

CExampleDlg::CExampleDlg(CWnd* pParent /*=NULL*/)

18



: CDialog(CExampleDlg::IDD
, pParent)

19

{

20

//{{AFX_DATA_INIT(CExampleDlg)

21

// NOTE: the ClassWizard will add member initialization here

22

//}}AFX_DATA_INIT

23


24

// Note that LoadIcon does not require a subsequent

25

// DestroyIcon in Win32

26


m_hIcon = AfxGetApp()
-
>LoadIcon(IDR_MAINFRAME);

27

}

28


29

vo
id CExampleDlg::DoDataExchange(CDataExchange* pDX)

30

{

31


CDialog::DoDataExchange(pDX);

32


33


//{{AFX_DATA_MAP(CExampleDlg)

34


// NOTE: the ClassWizard will add DDX and DDV calls here

35


//}}AFX_DATA_MAP

36

}

37


38

BEGIN_MESSAGE_MAP(CExampleDlg, CDialog)

39


//{{AFX_MSG_MAP
(CExampleDlg)

40


ON_WM_PAINT()

41


ON_WM_QUERYDRAGICON()

42


ON_BN_CLICKED(IDC_BUTTON1, OnButton1)

43


//}}AFX_MSG_MAP

44

END_MESSAGE_MAP()

45


46

///////////////////////////////////////////////////////////////////////
47

//////

48

// CExampleDlg message handlers

49


50


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



BOOL CExampleD
lg::OnInitDialog()

51

{

52


CDialog::OnInitDialog();

53


54


// Set the icon for this dialog.

55


// The framework does this automatically

56


// when the application's main window is not a dialog

57


SetIcon(m_hIcon, TRUE);


// Set big icon

58


SetIcon(m_hIcon, FALSE);


// Set small icon

59



60


// TODO: Add extra initialization here

61



62


return TRUE; // return TRUE unless you set the focus to a control

63

}

64


65

// If you add a minimize button to your dialog,

66

// you will need the code below to draw the icon.

67

// For MFC applicat
ions using the document/view model,

68

// this is automatically done for you by the framework.

69


70

void CExampleDlg::OnPaint()

71

{

72


if (IsIconic())

73


{

74


CPaintDC dc(this); // device context for painting

75


76


SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeH
dc(), 0);

77


78


// Center icon in client rectangle

79


int cxIcon = GetSystemMetrics(SM_CXICON);

80


int cyIcon = GetSystemMetrics(SM_CYICON);

81


CRect rect;

82


GetClientRect(&rect);

83


int x = (rect.Width()
-

cxIcon + 1) / 2;

84


int y = (rect.Height()
-

cyIcon + 1) / 2;

85


86


// Draw the icon

87


dc.DrawIcon(x, y, m_hIcon);

88


}

89


else

90


{

91


CDialog::OnPaint();

92


}

93

}

94


95

// The system calls this to obtain the cursor to display while

96

// the user drags the minimized window.

97

HCURSOR CExampleDlg::OnQueryDragI
con()

98

{

99


return (HCURSOR) m_hIcon;

100

}

101


102

103


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



//***********************************************************

104

// The next 2 macros are unspeakable hacks, straight from the

105

// Microsoft example, but they get the job done, keeping the

106

// code relatively easy to fo
llow. I DO NOT recommend following

107

// this style in real programs.

108

//***********************************************************

109


110

#define CHECKHR(x) {hr = x; if (FAILED(hr)) goto CleanUp;}

111

#define SAFERELEASE(p) {if (p) {(p)
-
>Release(); p = NULL;}}

112


113


114


115

HRE
SULT ReportError(MSXML::IXMLDOMParseError *pXMLError)

116

{

117


long line, linePos;

118


LONG errorCode;

119


BSTR pBURL, pBReason;

120


HRESULT hr;

121


122


CHECKHR(pXMLError
-
>get_line(&line));

123


CHECKHR(pXMLError
-
>get_linepos(&linePos));

124


CHECKHR(pXMLError
-
>get_errorCode(&e
rrorCode));

125


CHECKHR(pXMLError
-
>get_url(&pBURL));

126


CHECKHR(pXMLError
-
>get_reason(&pBReason));

127


128


fprintf(stderr, "%S", pBReason);

129


if (line > 0)

130


{

131


fprintf(stderr, "Error on line %d, position %d in
\
"%S
\
".
\
n",

132


line, linePos, pBURL);

133


}

134


135

CleanUp:

136


137


SysFreeString(pBURL);

138


SysFreeString(pBReason);

139


return E_FAIL;

140

}

141


142

HRESULT CheckLoad(MSXML::IXMLDOMDocument* pDoc)

143

{

144


MSXML::IXMLDOMParseError *pXMLError = NULL;

145


LONG errorCode = E_FAIL;

146


HRESULT hr;

147


148


CHECKHR(pDoc
-
>get_parseError(&p
XMLError));

149


CHECKHR(pXMLError
-
>get_errorCode(&errorCode));

150


if (errorCode != 0)

151


hr = ReportError(pXMLError);

152


153

CleanUp:

154


SAFERELEASE(pXMLError);

155


return errorCode;

156

}

157


158

HRESULT LoadDocument(MSXML::IXMLDOMDocument *pDoc, BSTR pBURL)

159

{

160


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




MSXML::IXMLDOM
ParseError* pXMLError = NULL;

161


VARIANT vURL;

162


VARIANT_BOOL vb;

163


HRESULT hr;

164


165


CHECKHR(pDoc
-
>put_async(false));

166


CHECKHR(pDoc
-
>put_validateOnParse(true));

167


168


// Load xml document from the given URL or file path

169


VariantInit(&vURL);

170


vURL.vt = VT_BSTR;

171


V_BSTR(&vURL) = pBURL;

172


CHECKHR(pDoc
-
>load(vURL, &vb));

173


174


CHECKHR(CheckLoad(pDoc));

175



176

CleanUp:

177


SAFERELEASE(pXMLError);

178


return hr;

179

}

180


181

void CExampleDlg::OnButton1()

182

{

183


HRESULT hr = S_OK;

184


MSXML::IXMLDOMDocum
ent* parser = NULL;

185


MSXML::IXMLDOMElement* employee = NULL;

186


MSXML::IXMLDOMNodeList* childNodes;

187


MSXML::IXMLDOMNode* node;

188


COleVariant firstName, lastName, spouseName;

189


COleVariant isMarried, age, salary, percentLastRaise;

190


BSTR xmlFile = NULL;

191


CString msg;

192


193


CoInitialize(NULL);

194


195


CHECKHR(CoCreateInstance(MSXML::CLSID_DOMDocument, NULL,

196


CLSCTX_INPROC_SERVER,

197


MSXML::IID_IXMLDOMDocument,

198


(void**)&parser) );

199


200


xmlFil
e = ::SysAllocString(L"ExampleSimple.xml");

201


CHECKHR(LoadDocument(parser, xmlFile) );

202


203


// access the elements in the xmldom tree

204


205


CHECKHR(parser
-
>get_documentElement(&employee) );

206


CHECKHR(employee
-
>get_childNodes(&childNodes) );

207



208


CHECKHR(childNo
des
-
>get_item(0, &node) );

209


CHECKHR(node
-
>get_nodeTypedValue(&firstName) );

210


211


CHECKHR(childNodes
-
>get_item(1, &node) );

212


CHECKHR(node
-
>get_nodeTypedValue(&lastName) );

213


214


CHECKHR(childNodes
-
>get_item(2, &node) );

215


CHECKHR(node
-
>get_nodeTypedValue(&isMa
rried) );

216


217


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




CHECKHR(childNodes
-
>get_item(3, &node) );

218


CHECKHR(node
-
>get_nodeTypedValue(&spouseName) );

219


220


CHECKHR(childNodes
-
>get_item(4, &node) );

221


CHECKHR(node
-
>get_nodeTypedValue(&age) );

222


223


CHECKHR(childNodes
-
>get_item(5, &node) );

224


CHECKHR(node
-
>
get_nodeTypedValue(&salary) );

225


226


CHECKHR(childNodes
-
>get_item(6, &node) );

227


CHECKHR(node
-
>get_nodeTypedValue(&percentLastRaise) );

228


229


msg.Format("Employee information
\
n
\
n"

230



"First Name:
\
t%S
\
n"

231


"Last Name:
\
t%S
\
n"

232


"Married
:
\
t
\
t%s
\
n"
// note the lower case %s !

233


"Spouse Name:
\
t%S
\
n"

234


"Age:
\
t
\
t%d
\
n"

235


"Salary:
\
t
\
t%d
\
n"

236


"Last Raise:
\
t%.2lf %%
\
n",

237




firstName.bstrVal,

238




lastName.bstrVal,

239




isMarried.boolVal ? "True" : "Fals
e",

240




spouseName.bstrVal,

241




age.intVal,

242





salary.intVal,

243




percentLastRaise.dblVal);

244


245


MessageBox(msg);

246


247

CleanUp:

248


SAFERELEASE(parser);

249


SAFERELEASE(childNodes);

250


SysFreeString(xmlFile);

251


252


CoUninitialize();

253

}
254


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example 10


Aggregate Data Struct
ures using Delphi

Referenced on slide 26


This code sample shows how to use the Microsoft
msxml

parser to create xml structures
that mimic the functionality of standard programming data structures like arrays, linked
lists and trees.


The sample is a small

application that has 3 tabs as shown in the following 3 figures.
Adding elements to the items displayed in the list box on the right produces the xml data
displayed at the bottom of the form.






Figure
6

-

An XML tree that mode
ls an array.


The
Arrays

page works like this: Enter a string in the
String to Set

box. Click the
Set

button to add elements to the array. To modify an element in the array, select it in the
listbox, then enter the new value in the edit box and press
Set
.
To clear the element,
select it and press the
DEL

key. Note than clearing elements does not cause the array to be
recompacted. You just wind up with empty elements.


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of





Figure
7

-

An XML tree that models a linked list.


The
Linked L
ists

page works like this: Enter a string in the
String to Set

box. Click
the
Set

button to add elements to the linked list. If an item is selected in the listbox when
you click the
Set

button, the new item is inserted at that location and the remaining it
ems
are pushed down. To delete an item, select it and press the
DEL

key.



Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of





Figure
8

-

An XML tree that models a tree.

The
Trees

page works like this: Enter a string in the
String to Set

box. Click the
Add
Sibling Node

button to
add elements to the tree. To add children to a node, select the
node in the tree, enter a string in the edit box and press the
Add Child Node

button. To
delete an item, select it in the tree and press the
DEL

key. Deleting a node causes all the
node’s chil
dren to also be deleted.


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




Delphi Code


unit DataStructures;

1


2

interface

3


4

uses

5


Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,

6


Dialogs, StdCtrls, ExtCtrls, ComCtrls, MSXML_TLB;

7


8

type

9


TFMMain = class(TForm)

10


PageControl1: TPageCont
rol;

11


TabSheet1: TTabSheet;

12


TabSheet2: TTabSheet;

13


TabSheet3: TTabSheet;

14


Label1: TLabel;

15


Label3: TLabel;

16


Panel1: TPanel;

17


GroupBox1: TGroupBox;

18


Label5: TLabel;

19


EditArrayStringToSet: TEdit;

20


ButtonArraySet: TButton;

21


L
istBoxItemsInArray: TListBox;

22


MemoXMLDataForArray: TMemo;

23


Label4: TLabel;

24


Label6: TLabel;

25


Label2: TLabel;

26


Panel2: TPanel;

27


Label7: TLabel;

28


GroupBox2: TGroupBox;

29


Label8: TLabel;

30


EditListStringToAdd: TEdit;

31


ButtonListAd
d: TButton;

32


ListBoxItemsInList: TListBox;

33


Label9: TLabel;

34


MemoXMLDataForList: TMemo;

35


Panel3: TPanel;

36


Label10: TLabel;

37


GroupBox3: TGroupBox;

38


Label11: TLabel;

39


EditTreeStringToAdd: TEdit;

40


ButtonTreeAddSibling: TButton;

41


Label12: TLabel;

42


MemoXMLDataForTree: TMemo;

43


TreeViewItems: TTreeView;

44


ButtonTreeAddChild: TButton;

45


procedure ListBoxItemsInArrayKeyDown(Sender: TObject;

46


var Key: Word;

47



Shift: TShiftState);

48


procedure ListBoxItemsInListKeyDown(Sender: TObject;

49


var Key: Word;

50


Shift: TShiftState);

51


procedure ButtonArraySetClick(Sender: TObject)
;

52


procedure FormCreate(Sender: TObject);

53


procedure ButtonListAddClick(Sender: TObject);

54


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




procedure ButtonTreeAddSiblingClick(Sender: TObject);

55


procedure TreeViewItemsKeyDown(Sender: TObject; var

56


Key: Word;

57


Shift: TShiftState);

58


procedure ButtonTreeAddChildClick(Sender: TObject);

59


60


private

61


XMLDOMArray: IXMLDOMDocument;

62


XMLDOMList: IXMLDOMDocument;

63


XMLDOMTree: IXMLDOMDocument;

64


65


procedure DeleteListBoxIt
em(TheListBox: TListBox);

66



67


procedure DeleteArrayXMLItem(TheIndex: Integer);

68


procedure SetArrayXMLItem(TheIndex: Integer; TheItem: String);

69


procedure DisplayArrayXML;

70



71


procedure DeleteListXMLItem(TheIndex: Integer);

72


procedure Add
ListXMLItem(TheIndex: Integer; TheItem: String);

73


procedure DisplayListXML;

74


75


procedure DeleteTreeXMLItem(TheTreeViewNode: TTreeNode);

76


procedure AddTreeXMLItem(TheParentNode: TTreeNode; TheText: String);

77


procedure DisplayTreeXML;

78


function

FindNodeWithAbsoluteIndex(TheAbsoluteIndex: Integer): IXMLDOMNode;

79


end;

80


81

var

82


FMMain: TFMMain;

83


84

implementation

85


86

{$R *.DFM}

87


88

procedure TFMMain.FormCreate(Sender: TObject);

89

var

90


Node: IXMLDOMNode;

91

begin

92


XMLDOMArray := CoDOMDocument.Create;

93


XMLDOMArr
ay.async := False;

94


XMLDOMArray.validateOnParse := True;

95


Node := XMLDOMArray.createNode(NODE_ELEMENT, 'Array', '');

96


XMLDOMArray.appendChild(Node);

97


DisplayArrayXML;

98


99


XMLDOMList := CoDOMDocument.Create;

100


XMLDOMList.async := False;

101


XMLDOMList.vali
dateOnParse := True;

102


Node := XMLDOMList.createNode(NODE_ELEMENT, 'List', '');

103


XMLDOMList.appendChild(Node);

104


DisplayListXML;

105


106


XMLDOMTree := CoDOMDocument.Create;

107


XMLDOMTree.async := False;

108


XMLDOMTree.validateOnParse := True;

109


Node := XMLDOMTree
.createNode(NODE_ELEMENT, 'Tree', '');

110


XMLDOMTree.appendChild(Node);

111


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




DisplayTreeXML;

112

end;

113


114

procedure TFMMain.DeleteListBoxItem(TheListBox: TListBox);

115

var

116


I: Integer;

117

begin

118


I := TheListBox.ItemIndex;

119


if I < 0 then Exit;

120


TheListBox.Items.Delete(T
heListBox.ItemIndex);

121


if I < TheListBox.Items.Count then

122


TheListBox.ItemIndex := I

123


else

124


TheListBox.ItemIndex := TheListBox.Items.Count
-
1;

125

end;

126


127

{******************************************************************************}

128

{*

Array methods *}

129

{******************************************************************************}

130


131

procedure TFMMain.ButtonArraySetClick(Sender: TObject);

132

var

133


I: Integer;

134

begin

135


I := ListBoxItemsInArray.ItemI
ndex;

136


ListBoxItemsInArray.Items.Delete(I);

137


ListBoxItemsInArray.Items.Insert(I, EditArrayStringToSet.Text);

138


SetArrayXMLItem(I, EditArrayStringToSet.Text);

139

end;

140


141

procedure TFMMain.SetArrayXMLItem(TheIndex: Integer; TheItem: String);

142

var

143


ArrayNode, No
de, NewNode: IXMLDOMNode;

144

begin

145


ArrayNode := XMLDOMArray.documentElement;

146


Node := ArrayNode.childNodes [TheIndex];

147


if Node = nil then

148


begin

149


NewNode := XMLDOMArray.createElement('Item');

150


NewNode.text := TheItem;

151


ArrayNode.appendChild(New
Node);

152


end else

153


Node.text := TheItem;

154


155


DisplayArrayXML;

156

end;

157


158

procedure TFMMain.DeleteArrayXMLItem(TheIndex: Integer);

159

var

160


ArrayNode, Node: IXMLDOMNode;

161

begin

162


ArrayNode := XMLDOMArray.documentElement;

163


Node := ArrayNode.childNodes [TheIndex];

164


if Node = nil then Exit;

165


Node.text := '';

166


DisplayArrayXML;

167

end;

168


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




169

procedure TFMMain.DisplayArrayXML;

170

begin

171


MemoXMLDataForArray.Lines.Clear;

172


MemoXMLDataForArray.Lines.Add(XMLDOMArray.xml);

173

end;

174


175

procedure TFMMain.ListBoxItemsInArrayKeyDown(Sender:
TObject;

176


var Key: Word;

177


Shift: TShiftState);

178

var

179


I: Integer;

180

begin

181


if Key <> VK_DELETE then Exit;

182


DeleteArrayXMLItem(ListBoxItemsInArray.ItemIndex);

183


I := List
BoxItemsInArray.ItemIndex;

184


if I < 0 then Exit;

185


ListBoxItemsInArray.Items [I] := '';

186

end;

187


188

{******************************************************************************}

189

{* List methods *}

190

{******************************************************************************}

191


192

procedure TFMMain.ButtonListAddClick(Sender: TObject);

193

var

194


I: Integer;

195

begin

196


I := ListBoxItemsInList.ItemIndex;

197


ListBoxItemsInList.Items.Insert(I, EditListStringToAdd.T
ext);

198


AddListXMLItem(I, EditListStringToAdd.Text);

199

end;

200


201

procedure TFMMain.AddListXMLItem(TheIndex: Integer; TheItem: String);

202

var

203


ListNode, Node, NewNode: IXMLDOMNode;

204

begin

205


ListNode := XMLDOMList.documentElement;

206


NewNode := XMLDOMList.createEleme
nt('Item');

207


NewNode.text := TheItem;

208


Node := ListNode.childNodes [TheIndex];

209


if Node = nil then

210


ListNode.appendChild(NewNode)

211


else

212


ListNode.insertBefore(NewNode, Node);

213


214


DisplayListXML;

215

end;

216


217

procedure TFMMain.DeleteListXMLItem(TheIndex:
Integer);

218

var

219


ListNode, Node: IXMLDOMNode;

220

begin

221


ListNode := XMLDOMList.documentElement;

222


Node := ListNode.childNodes [TheIndex];

223


if Node = nil then Exit;

224


ListNode.removeChild(Node);

225


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




DisplayListXML;

226

end;

227


228

procedure TFMMain.DisplayListXML;

229

begin

230


MemoXMLDataForList.Lines.Clear;

231


MemoXMLDataForList.Lines.Add(XMLDOMList.xml);

232

end;

233


234

procedure TFMMain.ListBoxItemsInListKeyDown(Sender: TObject;

235


var Key: Word;

236


Shif
t: TShiftState);

237

begin

238


if Key <> VK_DELETE then Exit;

239


DeleteListXMLItem(ListBoxItemsInList.ItemIndex);

240


DeleteListBoxItem(ListBoxItemsInList);

241

end;

242


243

{******************************************************************************}

244

{*

Tree methods *}

245

{******************************************************************************}

246


247

procedure TFMMain.ButtonTreeAddSiblingClick(Sender: TObject);

248

var

249


Node, ParentNode: TTreeNode;

250

begin

251


Node := T
reeViewItems.Selected;

252


if Node = nil then

253


ParentNode := nil

254


else

255


ParentNode := Node.Parent;

256


257


if Node = nil then

258


TreeViewItems.Items.AddChild(nil, EditTreeStringToAdd.Text)

259


else

260


TreeViewItems.Items.AddChild(Node.Parent, EditTreeStrin
gToAdd.Text);

261


TreeViewItems.FullExpand;

262


AddTreeXMLItem(ParentNode, EditTreeStringToAdd.Text);

263

end;

264


265

procedure TFMMain.ButtonTreeAddChildClick(Sender: TObject);

266

var

267


Node: TTreeNode;

268

begin

269


Node := TreeViewItems.Selected;

270


TreeViewItems.Items.AddChil
d(Node, EditTreeStringToAdd.Text);

271


TreeViewItems.FullExpand;

272


AddTreeXMLItem(Node, EditTreeStringToAdd.Text);

273

end;

274


275

procedure TFMMain.AddTreeXMLItem(TheParentNode: TTreeNode; TheText: String);

276

var

277


TreeNode, Node, NewNode: IXMLDOMNode;

278


NodeText: Stri
ng;

279


Level, ParentIndex: Integer;

280

begin

281


if TheParentNode = nil then

282


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




begin

283


Level := 0;

284


ParentIndex := 0;

285


end else

286


begin

287


Level := TheParentNode.Level + 1;

288


ParentIndex := TheParentNode.AbsoluteIndex;

289


end;

290


291


Inc(Level); // make lev
el numbers start at 1

292


TreeNode := XMLDOMTree.documentElement;

293


NodeText := Format('Level%d', [Level] );

294


NewNode := XMLDOMTree.createElement(NodeText);

295


NewNode.text := TheText;

296


297


Node := FindNodeWithAbsoluteIndex(ParentIndex);

298


299


if TheParentNode =
nil then

300


TreeNode.appendChild(NewNode)

301


else

302


Node.appendChild(NewNode);

303


304


DisplayTreeXML;

305

end;

306


307

// recursively descend the DOM tree until the i
-
th element is found

308

function TFMMain.FindNodeWithAbsoluteIndex(TheAbsoluteIndex: Integer):
309

IXMLDOMNode
;

310

var

311


XMLDOMNodeList: IXMLDOMNodeList;

312

begin

313


XMLDOMNodeList := XMLDOMTree.documentElement.getElementsByTagName('*');

314


Result := XMLDOMNodeList.item [TheAbsoluteIndex];

315

end;

316


317

procedure TFMMain.DeleteTreeXMLItem(TheTreeViewNode: TTreeNode);

318

var

319


Index:

Integer;

320


TreeNode, Node: IXMLDOMNode;

321

begin

322


if TheTreeViewNode = nil then

323


Index := 0

324


else

325


Index := TheTreeViewNode.AbsoluteIndex;

326


327


TreeNode := XMLDOMTree.documentElement;

328


Node := FindNodeWithAbsoluteIndex(Index);

329


if Node = nil then Exi
t;

330


331


if Index = 0 then

332


TreeNode.removeChild(Node)

333


else

334


Node.parentNode.removeChild(Node);

335


DisplayTreeXML;

336

end;

337


338

procedure TFMMain.DisplayTreeXML;

339


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



begin

340


MemoXMLDataForTree.Lines.Clear;

341


MemoXMLDataForTree.Lines.Add(XMLDOMTree.xml);

342

end;

343


344

pro
cedure TFMMain.TreeViewItemsKeyDown(Sender: TObject;

345


var Key: Word;

346


Shift: TShiftState);

347

var

348


Node: TTreeNode;

349

begin

350


if Key <> VK_DELETE then Exit;

351


352


Node := TreeViewItems.Se
lected;

353


if Node = nil then Exit;

354


355


DeleteTreeXMLItem(Node);

356


TreeViewItems.Selected := Node.Parent;

357


TreeViewItems.Items.Delete(Node);

358

end;

359


360

end.
361


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example 11


Modeling a Structured object in XML

Referenced on slide 27


This code sample shows how to us
e the Microsoft
msxml

parser to create an xml
document that encodes the fields and properties of a
Car

object. Running the script makes
the following message box appear:




Figure
9

-

The message box displayed by the JavaScript ex
ample.


Schema, in the file named
Schema
-
Object.xml


<?xml version="1.0"?>

1


2

<s:Schema xmlns:s="urn:schemas
-
microsoft
-
com:xml
-
data"

3


xmlns:dt="urn:schemas
-
microsoft
-
com:datatypes">

4



5


<s:ElementType name='Car' content='mixed' model='open'>

6


<s:AttributeType name='ID' dt:type='string'/>

7


<s:AttributeType name='Doors' dt:type='int'/>

8


</s:ElementType>

9



10

</s:Schema>

11


XML document referencing the schema in
Schema
-
Object.xml


<?xml version="1.0"?>

12


13

<Car xmlns:s="x
-
schema:Schema
-
Object.xml"
ID='MyCar' Doors='2'>

14


<Color> Red </Color>

15


<Engine>

16


<Power> 130 </Power>

17


<Size> 2400 </Size>

18


<Cylinders> 6 </Cylinders>

19


</Engine>

20

</Car>

21


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



JavaScript Code


<HTML>

1

<SCRIPT>

2


3


var parser, car;

4


var id, doors, color, engine, power, size,
cylinders;

5



6


parser = new ActiveXObject("Microsoft.XMLDOM");

7


parser.async = false;

8


parser.validateOnParse = true;

9


parser.load("UseSchema
-
Object.xml");

10


if (parser.parseError != 0)

11


alert(parser.parseError.reason);

12



13


car = parser
.documentElement;

14


id = car.attributes.getNamedItem("ID").text;

15


doors = car.attributes.getNamedItem("Doors").text;

16


color = car.childNodes.item(0).text;

17


engine = car.childNodes.item(1);

18


power = engine.childNodes.item
(0).text;

19


size = engine.childNodes.item(1).text;

20


cylinders = engine.childNodes.item(2).text;

21


22


alert("Car Description
\
n
\
n" +

23


"ID:
\
t
\
t" + id + "
\
n" +

24


"doors:
\
t
\
t" + doors + "
\
n" +

25


"color:
\
t
\
t" + color + "
\
n" +

26



"engine power:
\
t" + power + " HP
\
n" +

27


"engine size:
\
t" + size + " CC
\
n" +

28


"engine cylinders:
\
t" + cylinders + "
\
n
\
n");

29


30

</SCRIPT>

31

</HTML>
32


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



Example 12


Saving an ADO recordset in XML

Referenced on slide 28


This example displays th
e contents of a database table in a grid, as shown in the figure
below. The example uses the table
Country

in the sample Delphi database
DBDEMOS.
To
run this example, you will need to have Delphi installed on your machine, in order for the
database table an
d the OLEDB Data Links to be set up properly.





Figure
10

-

The contents of the country table
.


To view the data in XML format, click the
Save Recordset as XML

button, the switch
to the
View XML

tab. The program invokes the met
hod:


ADOQuery1.Recordset.Save(Name, adPersistXML);


to save the recordset into a file as xml. ADO 2.5 has a new method that allows you to
write the xml text into a string variable, making the operation much faster.


The xml is then displayed in the form w
ith the code:


Memo1.Lines.LoadFromFile(Name);


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




which just reads the file and displays it.

The following figure shows the XML data.




Figure
11

-

The record set as an XML document.



Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



unit Unit1;

1


2

interface

3


4

uses

5


Windows, Messag
es, SysUtils, Classes, Graphics, Controls, Forms,

6


Dialogs, Grids, DBGrids, Db, ADODB, StdCtrls, ExtCtrls, ComCtrls;

7


8

type

9


TForm1 = class(TForm)

10


ADOQuery1: TADOQuery;

11


ADOConnection1: TADOConnection;

12


DataSource1: TDataSource;

13


PageControl1
: TPageControl;

14


TabSheet1: TTabSheet;

15


TabSheet2: TTabSheet;

16


DBGrid1: TDBGrid;

17


Panel1: TPanel;

18


Button1: TButton;

19


Memo1: TMemo;

20


procedure Button1Click(Sender: TObject);

21


procedure FormCreate(Sender: TObject);

22

end;

23


24

var

25


Form1:

TForm1;

26


27

implementation

28


29

uses ADOR_TLB;

30


31

{$R *.DFM}

32


33

procedure TForm1.Button1Click(Sender: TObject);

34

const

35


Name = 'xmlrecordset.xml';

36

begin

37


if FileExists(Name) then

38


DeleteFile(Name);

39


40


ADOQuery1.Recordset.Save(Name, adPersistXML);

41


Memo1.Lines.L
oadFromFile(Name);

42

end;

43


44

procedure TForm1.FormCreate(Sender: TObject);

45

begin

46


PageControl1.ActivePageIndex := 0;

47

end;

48


49

end.
50


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of



The complete contents of the xml file produced are shown below.


<xml xmlns:s='uuid:BDC6E3F0
-
6DA3
-
11d1
-
A2A3
-
00AA00C14882'

1


xmlns:d
t='uuid:C2F41010
-
65B3
-
11d1
-
A29F
-
00AA00C14882'

2


xmlns:rs='urn:schemas
-
microsoft
-
com:rowset'

3


xmlns:z='#RowsetSchema'>

4


5

<s:Schema id='RowsetSchema'>

6


<s:ElementType name='row' content='eltOnly' rs:updatable='true'>

7



<s:attribute type='Name'/>

8



<s:attribute

type='Capital'/>

9



<s:attribute type='Continent'/>

10



<s:attribute type='Area'/>

11



<s:attribute type='Population'/>

12



<s:extends type='rs:rowbase'/>

13


</s:ElementType>

14


<s:AttributeType name='Name' rs:number='1' rs:nullable='true'

15




rs:maydefer='true' rs:w
riteunknown='true'

16


rs:basetable='country' rs:basecolumn='Name' rs:keycolumn='true'>

17



<s:datatype dt:type='string' dt:maxLength='24'/>

18


</s:AttributeType>

19


<s:AttributeType name='Capital' rs:number='2'

20


rs:nullable='true' rs:mayd
efer='true' rs:writeunknown='true'

21




rs:basetable='country' rs:basecolumn='Capital'>

22



<s:datatype dt:type='string' dt:maxLength='24'/>

23


</s:AttributeType>

24


<s:AttributeType name='Continent' rs:number='3'

25


rs:nullable='true' rs:maydefer='true
' rs:writeunknown='true'

26




rs:basetable='country' rs:basecolumn='Continent'>

27



<s:datatype dt:type='string' dt:maxLength='24'/>

28


</s:AttributeType>

29


<s:AttributeType name='Area' rs:number='4'

30


rs:nullable='true' rs:maydefer='true' rs:writeunk
nown='true'

31




rs:basetable='country' rs:basecolumn='Area'>

32



<s:datatype dt:type='float' dt:maxLength='8'

33


rs:precision='15' rs:fixedlength='true'/>

34


</s:AttributeType>

35


<s:AttributeType name='Population' rs:number='5'

36


rs:nullab
le='true' rs:maydefer='true' rs:writeunknown='true'

37




rs:basetable='country' rs:basecolumn='Population'>

38



<s:datatype dt:type='float' dt:maxLength='8'

39


rs:precision='15' rs:fixedlength='true'/>

40


</s:AttributeType>

41

</s:Schema>

42


43

<rs:data>

44


<z:
row Name='Argentina' Capital='Buenos Aires'

45


Continent='South America'

46




Area='2777815' Population='32300003'/>

47


<z:row Name='Bolivia' Capital='La Paz'

48


Continent='South America'

49


Area='1098575' Population='7300000'/
>

50


<z:row Name='Brazil' Capital='Brasilia'

51


Class Notes


Examp汥s

T敤 䙡楳on 2000
-

-


P慧攠


of




Continent='South America' Area='8511196'

52


Population='150400000'/>

53


<z:row Name='Canada' Capital='Ottawa'

54


Continent='North America' Area='9976147'

55


Population='
26500000'/>

56


<z:row Name='Chile' Capital='Santiago'

57


Continent='South America' Area='756943'

58


Population='13200000'/>

59


<z:row Name='Colombia' Capital='Bagota'

60


Continent='South America' Area='1138907'

61


Po
pulation='33000000'/>

62


<z:row Name='Cuba' Capital='Havana'

63


Continent='North America' Area='114524'

64


Population='10600000'/>

65


<z:row Name='Ecuador' Capital='Quito'

66


Continent='South America' Area='455502'

67



Population='10600000'/>

68


<z:row Name='El Salvador' Capital='San Salvador'

69


Continent='North America' Area='20865'

70


Population='5300000'/>

71


<z:row Name='Guyana' Capital='Georgetown'

72


Continent='South America' Area='2
14969'

73


Population='800000'/>

74


<z:row Name='Jamaica' Capital='Kingston'

75


Continent='North America' Area='11424'

76


Population='2500000'/>

77


<z:row Name='Mexico' Capital='Mexico City'

78


Continent='North Americ
a' Area='1967180'

79


Population='88600000'/>

80


<z:row Name='Nicaragua' Capital='Managua'

81


Continent='North America' Area='139000'

82


Population='3900000'/>

83


<z:row Name='Paraguay' Capital='Asuncion'

84


Continent
='South America' Area='406576'

85


Population='4660000'/>

86


<z:row Name='Peru' Capital='Lima'

87


Continent='South America' Area='1285215'

88


Population='21600000'/>

89


<z:row Name='United States of America' Capital='Washington'


90


Continent='North America' Area='9363130'

91


Population='249200000'/>

92


<z:row Name='Uruguay' Capital='Montevideo'

93


Continent='South America' Area='176140'

94


Population='3002000'/>

95


<z:row Name='Venezuela' C
apital='Caracas'

96


Continent='South America' Area='912047'

97


Population='19700000'/>

98

</rs:data>

99

</xml>

100