CodeSmith实用技巧(六):使用XML 属性
上一篇 / 下一篇 2007-09-26 14:24:55 文章类型: 转载
CodeSmith 允许我们存储 元数据在 XML 文件中,然后在执行模版时直接打开 XML 文件填写到属性面板中。
1 . XML Property With a Schema
1
<?
xml version="1.0" encoding="UTF-8"
?>
2
<
xs:schema
targetNamespace
=http://www.codesmithtools.com/PO
3
xmlns:xs
=http://www.w3.org/2001/XMLSchema
4
xmlns
=http://www.codesmithtools.com/PO
5
elementFormDefault
="qualified"
attributeFormDefault
="unqualified"
>
6
<
xs:element
name
="PurchaseOrder"
>
7
<
xs:complexType
>
8
<
xs:sequence
>
9
<
xs:element
name
="PONumber"
type
="xs:string"
/>
10
<
xs:element
name
="CustomerName"
type
="xs:string"
/>
11
<
xs:element
name
="CustomerCity"
type
="xs:string"
/>
12
<
xs:element
name
="CustomerState"
type
="xs:string"
/>
13
<
xs:element
name
="Items"
>
14
<
xs:complexType
>
15
<
xs:sequence
>
16
<
xs:element
name
="Item"
maxOccurs
="unbounded"
>
17
<
xs:complexType
>
18
<
xs:attribute
name
="ItemNumber"
type
="xs:string"
use
="required"
/>
19
<
xs:attribute
name
="Quantity"
type
="xs:integer"
use
="required"
/>
20
</
xs:complexType
>
21
</
xs:element
>
22
</
xs:sequence
>
23
</
xs:complexType
>
24
</
xs:element
>
25
</
xs:sequence
>
26
</
xs:complexType
>
27
</
xs:element
>
28
</
xs:schema
>
29
30

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

这是一个简单的带有Schema 的 XML Property 的例子:
利用这个 Schema 文件,我们可以定义一个 XML Property 来在运行时读去元数据。













在运行时,PurchaseOrder 属性在属性面板中显示为按钮,单击后弹出一个对话框供用户选择 XML 文件。
选择一个 XML 文件。在该例子 XML 文件内容如下:
1
<?
xml version="1.0" encoding="UTF-8"
?>
2
<
PurchaseOrder
xmlns
=http://www.codesmithtools.com/PO
3
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
>
4
<
PONumber
>
5271
</
PONumber
>
5
<
CustomerName
>
John Nelson
</
CustomerName
>
6
<
CustomerCity
>
Gamonetta
</
CustomerCity
>
7
<
CustomerState
>
MS
</
CustomerState
>
8
<
Items
>
9
<
Item
ItemNumber
="HM85"
Quantity
="12"
/>
10
<
Item
ItemNumber
="JR82"
Quantity
="4"
/>
11
<
Item
ItemNumber
="PR43"
Quantity
="6"
/>
12
</
Items
>
13
</
PurchaseOrder
>
14
15

2

3

4

5

6

7

8

9

10

11

12

13

14

15

生成后的代码如下:









2 . XML Property Without a Schema
这是一个不带 Schema 的 XML Property 的例子。这个模版在运行时可以访问任何 XML 文件。













概莫版对目标文件的属性并没有定义一个Schema ,所以属性在模版中是作为一个 XMLDocument 。如果我们选择的 XML 文件如下所示:
1
<?
xml version="1.0" encoding="UTF-8"
?>
2
<
Books
>
3
<
Book
>
UML 2.0 In a Nutshell
</
Book
>
4
<
Book
>
The Best Software Writing
</
Book
>
5
<
Book
>
Coder to Developer
</
Book
>
6
<
Book
>
Code Complete
</
Book
>
7
</
Books
>

2

3

4

5

6

7

生成后的代码:





