Anda di halaman 1dari 44

Bi 1 Tm hiu cu trc v c php ca XML

thy nh hng rng ln ca XML trong ngnh Cng Ngh Thng Tin cn i bn

ch cn rng XML l l do ca s hin hu (raison d'tre) ca Microsoft .Net. T WindowsXP tr i, bn trong y dy XML. Microsoft u t hn 3 t la M vo k thut ny, v trong tng lai gn y tt c phn mm ca Microsoft nu khng dn nh (c ported) qua .NET th t nht cng c .NET Enabled (dng cho .NET c). i song song vi .NET l SQLServer 2000, mt c s d liu h tr XML hon ton. C l bn nghe qua Web Services. l nhng dch v trn Web ta c th dng on-demand , tc l khi no cn cho chng trnh ca mnh, bng cch gi n theo phng php ging ging nh gi mt Hm (Function). Web Services c trin khai da vo XML v Http, chun dng gi cc trang Web. im quan trng ca k thut XML l n khng thuc ring v mt cng ty no, nhng l mt tiu chun c mi ngi cng nhn v c son ra bi World Wide Web Consortium - W3C (mt ban son tho vi s hin din ca tt c cc dn c mu mt trn giang h Tin hc) v nhng ai mun ng gp bng cch trao i qua Email. Bn thn ca XML tuy khng c g kh hiu, nhng cc cng c chun c nh ra lm vic vi XML nh Document Object Model - DOM, XPath, XSL, v.v.. th rt hu hiu, v chnh cc chun ny c pht trin khng ngng. Microsoft committed (nht quyt dn thn) vo XML ngay t u. Chng nhng c i din lm vic thng trc trong W3C m cn tch cc ng gp bng cch gi nhng ngh. V tr ca Microsoft v XML l khi tiu chun cha c hon thnh th cc sn phm ca Microsoft tun th (comply) nhng g c v c a s cng nhn v khi tiu chun hon thnh th tun th hon ton. Ci cng c XML sng gi nht ca Microsoft l ActiveX MSXML. N c dng trong Visual Basic 6, ASP (Active Server Pages) ca IIS v Internet Explorer t version 5.5. Hin nay MSXML c version 4.0. MSXML parse (c v phn tch) v validate (kim tra s hp l) XML file cho ta DOM, mt tree ca cc Nodes i din cc thnh phn bn trong XML. MSXML cng gip ta da vo mt XSL file transform (bin th) mt XML file thnh mt trang Web (HTML) hay mt XML khc.

XML l g? Mt cht lch s


Nh tt c chng ta u bit, XML l vit tt cho ch eXtensible Markup Language - nhng Markup Language (ngn ng nh du) l g? Trong ngnh n lot, ch th cho th sp ch v cch in mt bi v, tc gi hay ch bt thng v cc vng trn trong bn tho v ch thch bng mt ngn ng nh du tng t nh tc k. Ngn ng y c gi l Markup Language. XML l mt ngn ng nh du tng i mi v n l mt subset (mt phn nh hn) ca v n t (derived from) mt ngn ng nh du gi dn tn l Standard Generalized Markup Language (SGML). Ngn ng HTML cng da vo SGML, tht ra n l mt p dng ca SGML. SGML c pht minh bi Ed Mosher, Ray Lorie v Charles F. Goldfarb ca nhm IBM research vo nm 1969, khi con ngi t chn ln mt trng. Lc u n c tn l Generalized Markup Language (GML), v c thit k dng lm metalanguage, mt ngn ng c dng din t cc ngn ng khc - vn phm, ng vng ca chng ,.v.v.. Nm 1986, SGML c c quan ISO (International Standard Organisation) thu nhn (adopted) lm tiu chun lu tr v trao i d liu. Khi Tim Berners-Lee trin khai HyperText Markup Language - HTML dng cho cc trang Web hi u thp nin 1990, ng ta c nhc nh rng HTML l mt p dng ca SGML. V SGML rt rc ri, v HTML c nhiu gii hn nn nm 1996 t chc W3C thit k XML. XML version 1.0 c nh ngha trong h s February 1998 W3C Recommendation, ging nh mt Internet Request for Comments (RFC), l mt "tiu chun".

T HTML n XML
Trong mt trang Web, ngn ng nh du HTML dng cc cp Tags nh du v tr u v cui ca cc mnh d liu gip chng trnh trnh duyt (browser) parse (ngt khc phn tch) trang Web v hin th cc phn theo ngi thit k trang Web. Th d nh mt cu HTML di y:
<P align="center">Cho mng bn n thm <STRONG>Vovisoft</STRONG>Web site </P>

Cu code HTML trn c cha hai markup Tags, <P> v <STRONG>. Mi cp Tags gi d liu n nh du gia opening Tag v closing Tag. Hai closing Tags y l </P> v </STRONG>. Tt c nhng g nm bn trong mt cp Tags c gi l Element. ni thm c tnh ca mt Element, ta c th nht Attribute nh align

trong opening Tag ca Element y di dng AttributeName="value", th d nh align="center". V Tags trong HTML c dng format (trnh by) ti liu nn browser cn bit ngha ca mi Tag. Mt browser hay HTML parser s thu thp cc ch th sau t cu HTML trn: 1. Bt u mt Paragraph mi v t Text gia trang (<P align="center">). 2. Hin th cu Cho mng bn n thm 3. Hin th ch Vovisoft cch mnh m (<STRONG>Vovisoft</STRONG>). 4. Hin th cu Web site 5. Gp im cui ca Paragraph (</P>) x l on code HTML trn, chng nhng browser cn phi xc nh v tr cc Tags m cn phi hiu ngha ca mi Tag. V mi Tag c nga ring ca n, th d P cho Paragraph, STRONG nhn mnh, th d nh dng ch m (Bold). Ging nh HTML, XML n t SGML. N cng dng Tags encode data. im khc bit chnh gia HTML v XML l trong khi cc Tags ca HTML cha ngha v formatting (cch trnh by) cc d liu, th cc Tags ca XML cha ngha v cu trc ca cc d liu. Th d nh mt ti liu t hng (order) XML di y:
<Order OrderNo="1023"> <OrderDate>2002-3-27</OrderDate> <Customer>Peter Collingwood</Customer> <Item> <ProductID>1</ProductID> <Quantity>5</Quantity> </Item> <Item> <ProductID>4</ProductID> <Quantity>3</Quantity> </Item> </Order>

Ti liu ny ch cha d liu, khng nhc nh g n cch trnh by. iu ny c ngha l mt XML parser (chng trnh ngt khc v phn tch) khng cn phi hiu ngha ca cc Tags. N ch cn tm cc Tags v xc nh rng y l mt ti liu XML hp l. V browser khng cn phi hiu ngha ca cc Tags, nn ta c th dng Tag no cng c. l l do ngi ta dng ch eXtensible (m rng thm c), nhng khi dng ch vit tt th li chn X thay v e, c l v X nghe c v k b, hp dn hn. Chng ta hy quan st k hn cu trc ca mt XML. Trc ht, Element Order c Attribute OrderNo vi value 1023. Bn trong Element Order c:

Mt Child (con) Element OrderDate vi value 2002-3-27

Mt Child Element Customer vi value Peter Collingwood. Hai Child Elements Item, mi Element Item li cha mt Child Element ProductID v mt Child Element Quantity.

i khi ta mt Element vi tn ng hong, nhng khng cha mt value, l do l ta mun dng n nh mt Element Nhim (Optional), c cng c, khng c cng khng sao. Cch t nhin nht l gn ci closing Tag ngay sau opening Tag. Th d nh Empty (trng rng) Element MiddleInitial trong Element customer di y:
<Customer> <FirstName>Stephen</FirstName> <MiddleInitial></MiddleInitial> <LastName>King</LastName> </Customer>

C mt cch khc biu din Empty Element l b closing Tag v thm mt du "/" (slash) cui openning Tag. Ta c th vit li th d customer nh sau:
<Customer> <FirstName>Stephen</FirstName> <MiddleInitial/> <LastName>King</LastName> </Customer>

D nhin Empty Element cng c th c Attribute nh Element PhoneNumber th nh di y:


<Customer> <FirstName>Stephen</FirstName> <MiddleInitial></MiddleInitial> <LastName>King</LastName> <PhoneNumber Location="Home">9847 2635</PhoneNumber> <PhoneNumber Location="Work"></PhoneNumber> </Customer>

Biu din Data trong XML


Mt ti liu XML phi well-formed v valid. Mc du hai t ny nghe t t, nhng chng c ngha khc nhau. Mt XML well-formed l mt XML thch hp cho parser ch bin. Tc l XML tun th cc lut l v Tag, Element, Attribute , value .v.v.. cha bn trong parser c th nhn din v phn bit mi th. l mt XML well-formed cha chc cha ng nhng d liu hu dng trong cng vic lm n. L well-formed ch c ngha l XML c cu trc ng. hu dng cho cng vic lm n, XML chng nhng well-formed m cn cn phi valid. Mt ti liu XML valid khi n cha nhng data cn c trong loi ti liu loi hay class y. Th d mt XML t hng c th b i hi phi c mt Attribute OrderNo v mt Child Element Orderdate. Parser validate mt XML bng cch kim tra data trong XML xem c ng nh nh ngha trong mt Specification v loi ti liu XML y. Specification ny c th l mt Document Type Definition (DTD) hay mt Schema.

Chc na ta s ni n valid, by gi hy bn v well-formed. To mt ti liu XML well-formed well-formed, mt ti liu XML phi theo ng cc lut sau y: 1. Phi c mt root (gc) Element duy nht, gi l Document Element, n cha tt c cc Elements khc trong ti liu. 2. Mi opening Tag phi c mt closing Tag ging nh n. 3. Tags trong XML th case sensitive, tc l opening Tag v closing Tag phi c nh vn y nh nhau, ch hoa hay ch thng. 4. Mi Child Element phi nm trn bn trong Element cha ca n. 5. Attribute value trong XML phi c gi gia mt cp ngoc kp hay mt cp apostrophe. Lut th nht i hi mt root Element duy nht, nn ti liu di y khng wellformed v n khng c mt top level Element:
<Product ProductID="1">Chair</Product> <Product ProductID="2">Desk</Product>

Mt ti liu XML khng c root Element c gi l mt XML fragment (mnh). lm cho n well-formed ta cn phi thm mt root Element nh di y:
<Catalog> <Product ProductID="1">Chair</Product> <Product ProductID="2">Desk</Product> </Catalog>

Lut th hai ni rng mi opening Tag phi c mt closing Tag ging nh n. Tc l mi Tag m ra phi c ng li. Empty Element vit cch gn nh <MiddleInitial/> c gi l c Tag t ng li. Cc Tags khc phi c closing Tag. Ci XML di y khng well-formed v n c cha mt mt Tag <Item> thiu closing Tag </Item>:
<Order> <OrderDate>2002-6-14</OrderDate> <Customer>Helen Mooney</Customer> <Item> <ProductID>2</ProductID> <Quantity>1</Quantity> <Item> <ProductID>4</ProductID> <Quantity>3</Quantity> </Item> </Order>

lm cho n well-formed ta phi thm ci closing tag cho Element Item th nht:
<Order> <OrderDate>2002-6-14</OrderDate> <Customer>Helen Mooney</Customer> <Item> <ProductID>2</ProductID>

<Quantity>1</Quantity> </Item> <Item> <ProductID>4</ProductID> <Quantity>3</Quantity> </Item> </Order>

Lut th ba ni l tn Tag th case sensitive, tc l closing Tag phi nh vn y ht nh opening Tag, phn bit ch hoa, ch thng. Nh th <order> khc vi <Order>, ta khng th dng Tag </Order> ng Tag <order>. Ci XML di y khng wellformed v opening Tag v closing Tags ca Element OrderDate khng nh vn ging nhau:
<Order> <OrderDate>2001-01-01</Orderdate> <Customer>Graeme Malcolm</Customer> </Order>

Mun lm cho n well formed, ta phi sa ch d thnh ch hoa (uppercase) D nh sau:


<Order> <OrderDate>2001-01-01</OrderDate> <Customer>Graeme Malcolm</Customer> </Order>

Lut th t ni mi Child Element phi nm trn bn trong Element cha ca n, tc l khng th bt u mt Element mi khi Element ny cha chm dt. Th d nh ti liu XML di y khng well-formed v closing Tag ca Category hin ra trc closing Tag ca Product.
<Catalog> <Category CategoryName="Beverages"> <Product ProductID="1"> Coca-Cola </Category> </Product> </Catalog>

Mun sa cho n well-formed ta cn phi ng Tag Product trc nh di y:


<Catalog> <Category CategoryName="Beverages"> <Product ProductID="1"> Coca-Cola </Product> </Category> </Catalog>

Lut cui cng v ti liu XML well-formed i hi value ca Attribute phi c gi trong mt cp apostrophe hay ngoc kp. Ti liu di y khng well-form v cc Attribute values khng c ngoc ng hong, s 1 khng c du ngoc, s 2 c mt ci apostrophe, mt ci ngoc kp:
<Catalog> <Product ProductID=1>Chair</Product> <Product ProductID='2">Desk</Product>

</Catalog>

Processing Instructions v Comments Ngoi cc d liu cn thit cho cng vic lm n, mt ti liu XML cng c cha cc Processing Instructions (ch th v cch ch bin) cho parser v Comments (ghi ch) cho ngi c. Processing Instruction nm trong cp Tags <? v ?>. Thng thng n cho bit version ca XML Specification m parser cn lm theo. C khi n cng cho bit data trong XML dng encoding no, th d nh uft-8. Cn mt Attribute na l standalone. standalone cho parser bit l ti liu XML c th c validated mt mnh, khng cn n mt DTD hay Schema. Mc du mt ti liu XML well-formed khng cn c mt Processing Instruction, nhng thng thng ta mt Processing Instruction ng u ti liu, phn y c gi l prologue (gio u). Di y l mt th d c Processing Instruction trong prologue ca mt ti liu XML:
<?xml version="1.0" encoding="utf-8" <Order> <OrderDate>2002-6-14</OrderDate> <Customer>Helen Mooney</Customer> <Item> <ProductID>1</ProductID> <Quantity>2</Quantity> </Item> <Item> <ProductID>4</ProductID> <Quantity>1</Quantity> </Item> </Order> standalone="yes"?>

C mt loi Processing Instruction khc cng rt thng dng l cho bit tn ca stylesheet ca XML ny, th d nh:
<?xml-stylesheet type="text/xsl" href="order.xsl"?>

y ta cho XML stylesheet parser bit rng stylesheet thuc loi text/xsl v n c cha trong file tn order.xsl. Bn cng c th cho thm Comment bng cch dng cp Tags <!-- v --> nh sau:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <!-- Below are details of a purchase order. --> <Order> <OrderDate>2002-6-14</OrderDate> <Customer>Helen Mooney</Customer> <Item> <ProductID>1</ProductID> <Quantity>2</Quantity> </Item> <Item> <ProductID>4</ProductID>

<Quantity>1</Quantity> </Item> </Order>

Namespaces C mt nim rt quan trng trong XML l Namespace. N cho ta cch cng mt tn ca Element ni n hai th d liu khc nhau trong cng mt ti liu XML. Ging nh c hai hc sinh trng tn Tun trong lp hc, ta phi dng thm h ca chng phn bit, ta gi Tun Trn hay Tun L. Th d nh c mt order c ngi ta t trong tim sch nh sau:
<?xml version="1.0"?> <BookOrder OrderNo="1234"> <OrderDate>2001-01-01</OrderDate> <Customer> <Title>Mr.</Title> <FirstName>Graeme</FirstName> <LastName>Malcolm</LastName> </Customer> <Book> <Title>Treasure Island</Title> <Author>Robert Louis Stevenson</Author> </Book> </BookOrder>

Khi quan st k, ta thy c th c s nhm ln v cch dng Element Title. Trong ti liu c hai loi Title, mt ci dng cho khch hng Customer ni n danh hiu Mr., Mrs., Dr., cn ci kia ni n ta ca mt quyn sch Book. trnh s lm ln, bn c th dng Namespace ni r tn Element y thuc v ging h no. Ging h y l mt Universal Resource Identifier (URI). Mt URI c th l mt URL hay mt ch no nh ngha tnh cch c o ca n. Mt namespace cng khng cn phi ni n mt a ch Internet, n ch cn phi l c mt, khng hai. Bn c th khai bo namespaces trong mt Element bng cch dng Attribute xmlns (ns trong ch xmlns l vit tt cho namespace) bn cng c th khai bo mt default namespace p dng cho nhng g nm bn trong mt Element, ni bn khai bo namespace. Th d ci ti liu t hng c th c vit li nh sau:
<?xml version="1.0"?> <BookOrder OrderNo="1234"> <OrderDate>2001-01-01</OrderDate> <Customer xmlns="http://www.northwindtraders.com/customer"> <Title>Mr.</Title> <FirstName>Graeme</FirstName> <LastName>Malcolm</LastName> </Customer> <Book xmlns="http://www.northwindtraders.com/book"> <Title>Treasure Island</Title> <Author>Robert Louis Stevenson</Author> </Book>

</BookOrder>

Ta trnh c s nhm ln v bn trong Customer th dng namespace http://www.northwindtraders.com/customer v bn trong Book th dng namespace http://www.northwindtraders.com/book. Tuy nhin, ta s gii quyt lm sao nu trong order c nhiu customer v nhiu book. Nu c thay i namespace hoi trong ti liu th chng mt cht. Mt cch gii quyt l khai bo ch vit tt cho cc namespaces ngay u ti liu, trong root Element (tc l Document Element). Sau bn trong ti liu ta s prefix cc Element cn xc nhn namespace bng ch vit tt ca namespace n. Th d nh sau:
<?xml version="1.0"?> <BookOrder xmlns="http://www.northwindtraders.com/order" xmlns:cust="http://www.northwindtraders.com/customer" xmlns:book="http://www.northwindtraders.com/book" OrderNo="1234"> <OrderDate>2001-01-01</OrderDate> <cust:Customer> <cust:Title>Mr.</cust:Title> <cust:FirstName>Graeme</cust:FirstName> <cust:LastName>Malcolm</cust:LastName> </cust:Customer> <book:Book> <book:Title>Treasure Island</book:Title> <book:Author>Robert Louis Stevenson</book:Author> </book:Book> </BookOrder>

Trong ti liu XML trn ta dng 3 namespaces: mt default namespace tn http://www.northwindtraders.com/order, namespace http://www.northwindtraders.com/customer (vit tt l cust) v namespace http://www.northwindtraders.com/book (vit tt l book). Cc Elements v Attributes khng c prefix (tc l khng c ch tt ng trc) nh BookOrder, OrderNo, v OrderDate, c coi nh thuc v default namespace. nh du mt Element hay Attribute khng thuc v default namespace, mt ch tt, i din namespace s c gn lm prefix cho tn Element hay Attribute. Th d nh cust:LastName, book:Title. CDATA CDATA l khc d liu trong ti liu XML nm gia <![CDATA[ v ]]>. Data nm bn trong nhng CDATA c cho thng qua parser y nguyn, khng b sa i. im ny rt quan trng khi bn mun cho vo nhng d liu c cha nhng text c xem nh markup. Bn c th t nhng th d cho XML trong nhng CDATA v chng s c parser b qua. Khi dng XSL stylesheets transform mt XML file thnh HTML, c bt c scripting no bn cng phi t trong nhng CDATA. Di y l cc th d dng CDATA: <![CDATA[...place your data here...]]>

<SCRIPT> <![CDATA[ function warning() { alert("Watch out!"); } ]]> </SCRIPT> Entity References Entity ni n cch vit mt s du c bit c nh ngha trc trong XML. C 5 entities di y: Entity &apos; &amp; &gt; &lt; &quot; Description du apostrophe du ampersand du ln hn du nh hn du ngoc kp

Trong bi ti ta s hc v cch process (ch bin) mt ti liu XML.

Bi 2 i li trong XML bng XPATH (phn I)

Chng ta thy cu trc v c php ca XML tng i n gin. XML cho ta mt cch
chun trao i tin tc gia cc computers. Bc tip theo l tm hiu cch no mt chng

trnh ch bin (process) mt ti liu XML D nhin ch bin mt XML chng trnh ng dng phi c cch i li bn trong ti liu ly ra values ca cc Elements hay Attributes. Do ngi ta thit k ra ngn ng XML Path language, m ta gi tt l XPath. XPath ng mt vai tr quan trng trong cng tc trao i d liu gia cc computers hay gia cc chng trnh ng dng v n cho php ta la chn hay sng lc ra nhng tin tc no mnh mun trao i hay hin th. Nu khi lm vic vi c s d liu ta dng SQL statement Select .. from TableXYZ WHERE ... trch ra mt s records t mt table, th khi lm vic vi XML, mt table d liu nho nh, XPath cho ta nhng expressions v criteria (iu kin) ging ging nh clause WHERE trong SQL. XPath l mt chun process XML, cng ging nh SQL l mt chun lm vic vi c s d liu. Tin phung trong vic trin khai cc chng trnh p dng XPath l cng tc ca cc cng ty phn mm ln nh Microsoft, Oracle, Sun, IBM, v.v. S d ta cn c mt chun XPath l v n c p dng trong nhiu hon cnh, nn cn phi c mt l thuyt r rng, chnh xc. L thuyt v XPath hi kh khan nhng n c p dng trong mi k thut ca gia nh XML. Cho nn bn hy kin nhn nm vng nhng iu cn bn v n khi no gp ch ngi ta dng XPath th mnh nhn din v hiu c. So vi v thut, th XPath trong XML ging nh Tn php v cch th. Tp luyn Tn php th mi chn, tp th th nhm chn, nhng khng c hai th th ra chiu khng c cng lc, cha nh thua ri. Ta s ch hc nhng th thng dng trong XPath thi, nu bn mun c y chi tit v XPath th c th tham kho Specification ca n http://www.w3c.org/TR/xpath.

XML nh mt cy i vi XPath
XPath cho ta c php din t cch i li trong XML. Ta coi mt ti liu XML nh c i din bng mt tree (cy) c nhiu nodes. Mi Element hay Attribute l mt node. minh ha nim ny, bn hy quan st ti liu t hng (order) XML sau:

<?xml version="1.0"?> <Order OrderNo="1047"> <OrderDate>2002-03-26</OrderDate> <Customer>John Costello</Customer> <Item> <Product ProductID="1" UnitPrice="70">Chair</Product> <Quantity>6</Quantity> </Item> <Item> <Product ProductID="2" UnitPrice="250">Desk</Product>

<Quantity>1</Quantity> </Item> </Order>

Ta c th biu din XML trn bng mt Tree nh di y, trong node Element mu nu, node Attribute mu xanh:

Ch nh Location Path
Bn c th dng XPath expression ch nh Location Path (li i n v tr) n node no hay trch ra (tr v) mt hay nhiu nodes tha ng iu kin yu cu. XPath expression c th l tuyt i, tc l ly node gc lm chun hay tng i, tc l khi u t node va mi c chn. Node y c gi l context node (node vai chnh trong tnh hung).

C hai cch vit din t XPath Location, vit nguyn v vit tt. Trong c hai cch ta u dng du slash (/) ni n Document Element, tc l node gc. Ta c th i li trong cc node ca Tree ging ging nh cc node ca Windows System Directory m ta thy trong Panel bn tri ca Window Explorer. Ta cng s dng nhng k hiu nh slash /, mt chm . v hai chm .. ca Windows System File Folder cho cch vit tt trong XPath Location i xung cc nodes con, chu, ch nh context node, hay i ngc ln cc nodes t tin.

Location Path tuyt i


Chng ta hy tm vi location paths trong ci Tree ca ti liu XML v t hng ni trn. Mun chn ci node ca Element Order (n cng l Root Element) bng c php nguyn, ta s dng XPath expression sau y:

/child::Order
Dch ra c php tt, expression ny tr nn:

/Order
i ra nhnh ca Tree, ta s tm c node Customer bng cch dng XPath expression sau:

/child::Order/child::Customer
Sau y l XPath expression vit tt tng ng:

/Order/Customer
Nu bn mun ly ra mt node Attribute, bn phi ni r iu ny bng cch dng t cha kha (keyword) attribute trong cch vit nguyn hay dng character @ trong c php tt. Do ly Attribute OrderNo ca Element Order, ta s dng XPath expression sau:

/child::Order/attribute::OrderNo
C php tt cho Attribute OrderNo l:

/Order/@OrderNo
trch ra cc nodes con chu, tc l cc nodes nhnh xa hn, ta dng keyword descendant trong c php nguyn hay mt double slash (//) trong c php tt. Th d, ly ra cc nodes Product trong ti liu, bn c th dng expression location path sau:

/child::Order/descendant::Product

C php tt tng ng l:

/Order//Product
Bn cng c th dng wildcards (l bi Joker) ni n nhng nodes m tn ca chng khng thnh vn . Th d, du asterisk (*) wildcard ch nh bt c node tn no. Location path sau y chn tt c cc nodes con ca Element Order:

/child::Order/child::*
C php tt tng ng l:

/Order/*

Location Path tng i


Nhiu khi XPath location paths l tng i vi context node, trong trng hp y location path din t cch ly ra mt node hay mt s (set of) nodes tng i vi context node. Th d nh, nu Element Item th nht trong order l context node, th location path tng i trch ra Element con Quantity l:

child::Quantity
Trong c php tt, location path tng i l:

Quantity
Tng t nh vy, ly ra Attribute ProductID ca Element con Product, ci location path tng i l:

child::Product/attribute::ProductID
Expression y dch ra c php tt l:

Product/@ProductID
i ngc ln pha trn ca Tree, ta dng keyword parent (cha). Dng tt tng ng ca keyword ny l hai du chm (..). Th d nu context node l Element OrderDate, th Attribute OrderNo c th c ly ra t Element Order bng cch dng location path tng i sau:

parent::Order/attribute::OrderNo
l c php ny ch tr v mt tr s khi node cha tn Order. Nu mun ly ra Attribute OrderNo t node cha khng cn bit n tn g bn phi dng expression sau:

parent::*/attribute::OrderNo
Vit theo kiu tt n gin hn v bn khng cn phi cung cp tn ca node cha. Bn c th ni n node cha bng cch dng hai du chm (..) nh sau:

../@OrderNo
Ngoi ra, bn c th ni n chnh context node bng cch dng hoc keyword self hoc mt du chm (.). iu ny rt tin trong vi trng hp, nht l khi bn mun bit current context node l node no.

Dng iu kin trong Location Path


Bn c th gii hn s nodes ly v bng cch gn thm iu kin sng lc vo location path. Ci iu kin gii hn mt hay nhiu nodes c thp vo expression bn trong mt cp ngoc vung ([]). Th d, ly ra mi Element Product c Attribute UnitPrice ln hn 70, bn c th dng XPath expression sau y:

/child::Order/child::Item/child::Product[attribute::UnitPrice> 70]
Trong c php tt, n l:

/Order/Item/Product[@UnitPrice>70]
Trong expression ca iu kin bn cng c th dng Xpath tng i , do trong expression iu kin bn c th dng bt c node no trong th bc. Th d sau y ly v nhng nodes Item c Element con Product vi Attibute ProductID tr s bng 1:

/child::Order/child::Item[child::Product/attribute::ProductID= 1]
Dch ra c php tt, ta c:

/Order/Item[Product/@ProductID=1]

Bi 3 i li trong XML bng XPATH (phn II)


Collections
Ci b (Set of) Nodes do XPath tr v c gi l Collection. Thng thng trong lp trnh, t "Collection" c dng ni n mt tp hp cc objects ng loi. Ta c th ln lt i qua (iterate through) cc objects trong mt Collection nhng khng c bo m th t ca chng, tc l gp object no trc hay object no sau. Tri li, trong chun XPath, khi mt Collection c tr v bi mt XPath Query (hi), n gi nguyn th t cc Nodes v cp bc ca chng trong ti liu XML. Tc l nu XPath tr v mt cnh cc nodes th tr nhng nodes khng tha iu kin, cc node cn li vn gi ng v tr trn cnh. V cc Attributes ca mt Element khng c th t, nn chng c th nm ln xn trong mt Collection.

Indexing trong mt Collection


Mt Collection ca Nodes c xem nh mt Array. Mun ni trc tip n mt Node trong Collection ta c th dng mt index trong cp ngoc vung. Node th nht c Index l 1. Cp ngoc vung ([]) c precedence cao hn (c tnh trc) du slash(/) hay hai du slash (//). Di y l hai th d: Expression author[1] author[firstname][3] Element author u tin. Element author th ba c mt Element firstname con. ngha

Mi lin h (Axes)
Mt location path dng mt Axis ch nh mi lin h gia cc Nodes c chn i vi context node. Sau y l bng lit k y cc axes: Axes
ancestor::

ngha T tin ca context node.

Nhng t tin ca context node gm c cha, ng ni, ancestor:: axis lun lun k c root node tr khi chn node.
ancestor-or-self::

Chnh context node v t tin ca n.

Ci ancestor-or-self:: axis lun lun k c root no


attribute::

Cc Attributes ca context node.

Nu context node khng phi l mt Element th chc c rng.


child::

Con ci ca context node.

Mt con l bt c node no nm ngay di context nod nhin, Attribute hay Namespace nodes khng c xem context node.
descendant::

Con chu ca context node.

Con chu l con, chu, cht, .v.v., do descendant:: cha Attribute hay Namespace nodes.
following::

Mi nodes hin ra sau context node trn tree, khng k con hay Namespace nodes. Mi nodes em (nm sau) context node.

following-sibling::

axis ni n ch nhng Nodes Node cha, nm trn tree sau context node. Axis khng trc context node.
following-sibling::

Nu context node l Attribute hay Namespace th foll axis s trng rng.

namespace::

Nhng Namespace nodes ca context node.

Mi namespace c mt namespace node trong scope (p context node.

Nu context node khng phi l mt Element th Axis s


parent::

Node cha ca context node, nu n c cha.

Node cha l node nm ngay pha trn context node trn


preceding::

Mi nodes hin ra trc context node trn tree, khng k c Attribute nodes, hay Namespace nodes.

Mt cch nhn din preceding:: axis l mi nodes trc khi context node bt u.
preceding-sibling::

Mi nodes anh (nm trc) context node.

axis ni n ch nhng Nodes Node cha, nm trn tree trc context node.
preceding-sibling::

Nu context node l Attribute hay Namespace th prec axis s trng rng.


self::

L chnh context node.

Sng lc (Filters)
Nh ta thy trn, gii hn ch ly ra nhng Nodes tha ng mt iu kin, ta gn mt Filter (sng lc) vo Collection. Filter y l mt Clause ging ging Clause WHERE trong ngn ng SQL ca c s d liu. Nu mt Collection nm gia mt filter, n s cho kt qu TRUE nu Collection tr v t nht mt Node v FALSE nu Collection trng rng (empty). Th d expression author/degree c ngha rng hm bin i Collection ra tr s Boolean s c gi tr TRUE nu hin ha mt Element author c Element con tn degree. Filters lun lun c tnh theo context ca n. Ni mt cch khc, ci expression book[author] c ngha l cho mi Element book tm thy, n s c th xem c cha mt Element con tn author khng. Tng t nh vy, book[author = 'Brown'] c ngha rng cho mi Element book tm thy, n s c th xem c cha mt Element con tn author vi tr s bng Brown khng.

Ta c th dng du chm (.) khm current context node. Th d nh, book[. = 'Dreams'] c ngha rng cho mi Element book tm thy trong current context, n s c th xem c tr s bng Dreams khng. Di y l mt t th d: Expression book[excerpt] book[excerpt]/title ngha Mi Element book c cha t nht mt Element excerpt. Mi Element title nm trong nhng Element book c cha Element excerpt.

book[excerpt]/author[degree]

Mi Element author c cha t nht mt Element degree v nhng Elements book c cha t nht mt Element excerpt

book[author/degree]

Mi Element book c cha t nht mt Element author vi Element degree con.

book[excerpt][title]

Mi Element book c cha t nht mt Element excerpt v Element title.

So snh
so snh hai objects trong XPath ta dng du (=) cho bng nhau v (!= ) cho khng bng nhau. Mi Element v Attributes l string, nhng c Typecast (xem nh ) nhng con s khi em ra so snh. Expression author[lastname = "Smith"] ngha

Mi Element author c cha t nht mt Element lastname bng Smith.

author[lastname[1] = "Smith"]

Mi Element author c Element lastname con u tin vi Smith.

author/degree[@from != "Harvard"]

Mi Element degree, l con mt Element author, v c m from vi tr s khng phi l "Harvard".

author[lastname = /editor/lastname]

Mi Element author c cha mt Element lastname bng v lastname l con ca root Element editor. Mi Element author c tr s string l John Hamilton.

author[. = "John Hamilton"]

Operator Union | (hp li)


Ngn ng Xpath h tr Operator Union, ging nh Logical OR (hoc l). Di y l vi th d: Expression firstname | lastname (bookstore/book | bookstore/magazine) book | book/author (book | magazine)/price ngha

Mi Element firstname v lastname trong current context.

Mi Element book hay magazine l con mt Element book

Mi Element book hay Element author l con nhng Eleme

Mi Element price l con ca Element book hay Element m

Th loi Node (Node Type Tests)


chn nhng loi Node khc hn l Element node, ta dng Node-Type Test. Mc ch ca vic dng Node-Type test l ch nh s la chn khc thng. Th d nh, descendant::text() cho ta mi text nodes l con chu ca context node, d rng loi node chnh ca con chu context node l Element. C 4 loi Node-Type tests nh lit k di y. Node type comment() Tr v mi comment node. Th d

following::comment() chn mi comm hin ra sau context node.

node()

mi node.

preceding::node() chn mi nodes hi context node.

processing-instruction()

mi processing instruction node.

self::processing instruction() chn m

instruction nodes trong context node. text() mi text node.

child::text() chn mi text nodes l co context node.

Th Node nhm vo loi Processing Instruction


Mt node test c th chn processing instruction thuc loi no, tc l chn mc tiu (target). C php ca mt loi test nh th l:

processing-instruction("target")
Th d node test sau y tr v mi processing instruction nodes c nhc n mt XSL stylesheet trong ti liu:

/child::processing-instruction("xml-stylesheet")

Thm mt s th d Location Path


Expression ./author ngha Mi Element author trong current context. Expresion ny tng ng vi expression trong hng k. Mi Element author trong current context. Document (Root) Element tn bookstore ca ti liu ny. Mi Element author trong ti liu.

author /bookstore //author book[/bookstore/@specialty = @style]

Mi Element book c Attribute style vi value bng value c specialty ca Document Element bookstore ca ti liu. Mi Element firstname con ca cc Elements author.

author/firstname bookstore//title

Mi Element title mt hay nhiu bc thp hn, tc l con c Element bookstore. Lu l expression ny khc vi expre

hng k. bookstore/*/title bookstore//book/excerpt//emph Mi Element title chu ca cc bookstore. Mi Element emph bt c ni no di excerpt l con ca elements book , bt c ni no di element bookstore.

.//title author/* book/*/lastname */* *[@specialty] @style price/@exchange

Mi Element title mt hay nhiu bc thp hn current cont Mi Element l con ca cc elements con author.

Mi Element lastname l chu ca cc elements con book. Mi Element chu ca current context node. Mi Element con c Attribute specialty. Attribute style ca current context node.

Attribute exchange ca nhng Elements price trong curren l nhng Elements price ca current context node.

price/@exchange/total

Tr v mt node set trng rng, v Attributes khng c Elem Expression ny c chp nhn trong vn phm ca XML P Language, nhng khng tht s hp l.

book[@style]

Mi Element book c Attribute style trong current context Lu phn nm trong ngoc vung l iu kin ca Elemen

book/@style

Attribute style ca mi Element booktrong current context y khng c iu kin nh hng trn. Ta ni n Attribu Element nm bn phi nht. Mi Attributes ca current context node. Element author th nht trong current context node.

@* author[1]

author[firstname][3] my:book my:*

Element author th ba c mt Element con firstname. Element book t namespace my. Mi Element trong namespace my.

Bi 4 XSL Style Sheets (phn I)

X ML l cch tuyt diu cho ta sp xp d liu trao i chng gia cc t chc v gia cc
chng trnh ng dng. Tuy nhin, chng chng th chy, ta s khm ph s a din ca c s d liu khp ni. V ngay c c chun XML ri, ta vn cn mt cng c hiu lc trnh by d liu trong nhiu kiu khc nhau thch hp cho p dng ch bin mt ni khc. XSL - eXtensible Style Sheet (nhng trang din t dng iu) l mt ngn ng chun gip ta bin i (transform) mt ti liu XML ra format khc, nh HTML, Wireless (v tuyn in) Markup Language (WML), v ngay c mt XML khc. Lc nguyn thy, XSL c thit k sanh ra nhiu HTML trong nhng dng khc nhau ty theo Style sheet. Tc l XSL thm dng iu cho XML, v chnh bn cht ca XML ch l mt cu trc ca nhng mnh d liu. Th d ta c hai Style sheet versions cho mt XML, mt ci dng to ra HTML cho trang Web thng thng trn computer, cn ci kia to ra trang Web dng cho Mobile Phone hay Pocket PC, nhng dng c c mn nh nh. C hai trang Web u cha cng mt s d liu, c th trn mn nh nh th gii hn nhng d liu quan trng thi, nhng cch trnh by c th rt khc nhau. Tuy nhin, sau khng lu, ngi ta thy XML c th c XSL bin i ra bt c Output Format no, ngay c chnh XML. C mt version mi, rt hay ca XSL va ra i. N c gi l XSL Transformations (XSLT).

Chng ta s ln lt hc cc c php thng dng ca XSL. Tuy khng nhiu, nhng n gip bn c mt nim cn bn v k thut ny bn c th bt u dng XSL style sheets bin ch d liu trong ti liu XML. Mun c mt XSL reference y , bn c th thm trang http://www.w3.org/Style/XSL. Nn nh l ging nh XPath, XSL v XSLT ch l nhng tiu chun n nh nhng g ta i hi mt chng trnh p dng c thc hin h tr chng cn phi c. Tuy nhin, ai trin khai chng trnh , v bng ngn ng lp trnh no cng c. Th d nh Microsoft cho ta MSXML version 3 dng XSL v XSLT.

Nhng trang XSL Style Sheet


Nhng trang XSL nh ngha nhng style sheets (trang dng iu) ta c th p dng vo nhng ti liu XML. Mt style sheet cha nhng ch dn (instructions) bo mt XML parser lm cch no pht sinh (generate) ra mt ti liu trnh duyt kt qu cho nhng d liu trong mt ti liu XML. Bn thn XSL style sheet cng l mt XML well-formed nhng n cha nhng lnh (commands) XSL v nhng cu HTML text dng y nguyn cho output. XML parser nhn din c cc lnh trong mt XSL, bn phi khai bo (declare) mt namespace trong root element, thng thng vi mt prefix xsl. Mt Style sheet thng thng cha mt trong hai namespaces: ci namespace XSL nguyn thy (http://www.w3.org/TR/WD-xsl) hay ci namespace mi XSLT (http://www.w3.org/1999/XSL/Transform). Microsoft XML parser (MSXML) t version 3.0 tr ln u h tr c hai namespaces. Xin lu l Internet Explorer version 5.x dng MSXML 2.5, nn khng h tr namespace XSLT. Mun khc phc tr ngi y, hoc l bn ci t Internet Explorer version 6, hoc l bn ci MSXML3 trong Replace mode bng cch dng cng c tn Xmlinst.exe thm chc nng h tr namespace XSLT trong IE v5.x. Ci Root Element trong mt ti liu XSL document thng thng l mt Element stylesheet. N cha mt hay nhiu Element Template c matched (cp i v ging nhau) vi d liu trong ti liu XML, th d nh ti liu t hng (order) di y:
<?xml version="1.0"?> <Order OrderNo="1047"> <OrderDate>2002-03-26</OrderDate> <Customer>John Costello</Customer> <Item> <Product ProductID="1" UnitPrice="70">Chair</Product> <Quantity>6</Quantity> </Item>

<Item> <Product ProductID="2" UnitPrice="250">Desk</Product> <Quantity>1</Quantity> </Item> </Order>

V chnh XSL style sheet cng l mt ti liu XML, nn n phi tun theo mi lut v mt XML well-formed. Sau y l mt XSL style sheet n gin c th c p dng vo ti liu order:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

Style sheet ny da trn namespace XSLT v cha vn vn mt template (bng km in) c p dng vo Root (biu hiu bng du slash / l tr s ca Attribute match) ca ti lu XML v mi Element bn trong ca n. Mt template tht th gm c mt lot Tags HTML s hin ra trong h s kt qu, nhng trong trng hp ny ci Template khng lm chuyn g hu ch; n ch output (cho ra) mt ti liu HTML y nguyn nh nm trong XSL v khng c cha d liu g t h s input XML. merge (ha ng) cc d liu trong XML vo XSL template, bn cn phi dng mt t lnh (commands) XSL.

Lnh value-of
XSL nh ngha mt s lnh ch bin (processing commands) trch d liu ra t mt ti liu XML v ha n vo mt h s kt qu. Ci lnh cn bn v hu dng nht trong s ny l lnh value-of. Lnh value-of chn tr s (value) ca mt Element hay Attribute no trong XML v ha n vi h s output. Lnh value-of c dng mt XML Element trong XSL. N dng mt Attribute tn select c value l mt XPath Location Path trch ra mt Node. Kt qu l value ca (value-of) Node y. Do , kh hn ln trc, by gi ta c th trnh by d liu ca XML vi lnh value-of nh sau:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML>

<HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: <xsl:value-of select="Order/@OrderNo"/> </P> <P>Date: <xsl:value-of select="Order/OrderDate"/> </P> <P>Customer: <xsl:value-of select="Order/Customer"/> </P> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

Ci Style sheet k ny trch ra Attribute OrderNo v tr s ca cc Elements OrderDate v Customer t Element Order bng cch dng mt XPath location path. Lu l cc XPath expressions y th tng i vi context node ch nh trong match parameter ca Element template (trong trng hp ny l Root Element, biu hiu bng du slash / ). p dng Style sheet ny vo h s t hng (order) XML ta s c HTML sau y:
<HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: 1047</P> <P>Date: 2002-03-26</P> <P>Customer: John Costello</P> </BODY> </HTML>

Lnh for-each
Trong mt ti liu XML, c th c nhiu Elements mang cng mt tn ni n mt danh sch nhng th tong t. Th d trong ti liu t hng c hai Element Item din t hai mn hng c t. Hu ht ngn ng lp trnh cho ta phng tin p dng cng mt cch ch bin cho mi mn trong nhm. Nh trong Visual Basic ta c FOR loop hay DO loop iterate qua tng mn trong b. Trong XSL cng th, bn c th dng lnh for-each i ln lt qua tng Element trong nhm, bng cch dng Attribute select ch nh nhng nodes m bn mun lm vic.

Th d ta c th lm cho ci Style sheet hay hn bng cch lit k cc Item trong Order thnh mt table:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: <xsl:value-of select="Order/@OrderNo"/> </P> <P>Date: <xsl:value-of select="Order/OrderDate"/> </P> <P>Customer: <xsl:value-of select="Order/Customer"/> </P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD> </TR> <xsl:for-each select="Order/Item"> <TR> <TD> <xsl:value-of select="Product/@ProductID"/> </TD> <TD> <xsl:value-of select="Product"/> </TD> <TD> <xsl:value-of select="Product/@UnitPrice"/> </TD> <TD> <xsl:value-of select="Quantity"/> </TD> </TR> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

Ln ny trong Style sheet, ta bo parser i qua tng Element Item ly ra Attributes ProductID v UnitPrice ca Element Product , v values ca Elements Product v Quantity, ri cho vo table.

Lu y cc XPath expressions tng i dng ci Node ch nh trong lnh for-each lm context node. Trong trng hp ny n l Node Item. Cui ca for-each loop l closing Tag ca Element for-each (</xsl:for-each>) . Style sheet trn ny khi p dng vo ti liu t hng s cho ra HTML sau y:
<HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: 1047</P> <P>Date: 2002-03-26</P> <P>Customer: John Costello</P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD> </TR> <TR> <TD>1</TD> <TD>Chair</TD> <TD>70</TD> <TD>6</TD> </TR> <TR> <TD>2</TD> <TD>Desk</TD> <TD>250</TD> <TD>1</TD> </TR> </TABLE> </BODY> </HTML>

Phn BODY ca HTML trn hin th nh sau:

Customer Order Order No: 1047 Date: 2002-03-26 Customer: John Costello
ProductID Product Name Price Quantity Ordered

1 2

Chair Desk

70

250 1

Lnh Attribute
i khi ta mun to ra thm mt Attribute trong h s output vi mt tr s ly t ti liu XML input. Th d nh tng ng vi mi tn ca mt Product, bn mun to ra mt hyperlink chuyn (pass) ci ProductID qua mt trang Web khc, ni s hin th chi tit v mt hng ny. to ra mt hyperlink trong mt h s HTML, bn cn to ra mt Element A (Anchor) vi mt Attribute href. Bn c th dng lnh Attribute ca XSL thc hin chuyn y nh minh ha trong Style sheet di y:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: <xsl:value-of select="Order/@OrderNo"/> </P> <P>Date: <xsl:value-of select="Order/OrderDate"/> </P> <P>Customer: <xsl:value-of select="Order/Customer"/> </P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD> </TR> <xsl:for-each select="Order/Item"> <TR> <TD> <xsl:value-of select="Product/@ProductID"/> </TD> <TD> <A> <xsl:attribute name="HREF">Products.asp?ProductID=

<xsl:value-of select="Product/@ProductID"/> </xsl:attribute> <xsl:value-of select="Product"/> </A> </TD> <TD> <xsl:value-of select="Product/@UnitPrice"/> </TD> <TD> <xsl:value-of select="Quantity"/> </TD> </TR> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

p dng Style sheet ny vo ti liu t hng XML, bn s c h s HTML sau:


<HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: 1047</P> <P>Date: 2002-03-26</P> <P>Customer: John Costello</P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD> </TR> <TR> <TD>1</TD> <TD> <A HREF="Products.asp?ProductID=1">Chair</A> </TD> <TD>70</TD> <TD>6</TD> </TR> <TR> <TD>2</TD> <TD> <A HREF="Products.asp?ProductID=2">Desk</A> </TD> <TD>250</TD> <TD>1</TD> </TR> </TABLE> </BODY>

</HTML>

Phn BODY ca HTML trn hin th nh sau:

Customer Order Order No: 1047 Date: 2002-03-26 Customer: John Costello
ProductID Product Name Price Quantity Ordered 1 2 Chair Desk 70 6

250 1

Bn c th Mouse cursor ln ch Chair hay ch Desk thy tn hyperlink ca chng hin th trong status bar ca browser. (cn tip)

Bi 5 XSL Style Sheets (phn II)


Cc lnh v iu kin
Ging nh trong ngn ng lp trnh thng thng ta c cc instructions v iu kin nh IF, SELECT CASE, ELSE .v.v.. la chn, trong XSL ta c cc lnh v iu kin nh xsl:if, xsl:choose, xsl:when, v xsl:otherwise. Khi expression ca Element xsl:if, xsl:when, hay xsl:otherwise c tr s true, th ci Template nm bn trong n s c to ra (instantiated).

Thng thng, nu cng vic th tnh n gin ta dng xsl:if. Nu n hi rc ri v ty theo trng hp ta phi lm nhng cng tc khc nhau th ta dng choose/when/otherwise. Tr s ca Attribute test ca xsl:if v xsl:when l mt expression tnh. Expression ny c th l mt so snh hay mt expression loi XPath. Kt qu vic tnh ny s l true nu n tr v mt trong cc tr s sau y:

Mt Mt Mt Mt

b node c t nht mt node con s khc zero mnh (fragment) Tree text string khng phi l trng rng (non-empty)

minh ha cch dng cc lnh XSL v iu kin ta s dng h s ngun tn catalog.xml sau y:
<?xml version="1.0"?> <catalog> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id="bk107"> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description> </book> <book id="bk108"> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects.</description> </book> <book id="bk109"> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date>

<description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.</description> </book> <book id="bk110"> <author>O'Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description> </book> </catalog>

Di y l mt th d dng xsl:if:
<xsl:for-each select="//book"> <tr> <td> <xsl:value-of select="title"/> </td> <td> <xsl:if test="price > 6"> <xsl:attribute name="bgcolor">cyan</xsl:attribute> </xsl:if> <xsl:value-of select="price"/> </td> </tr> </xsl:for-each>

Trong th d trn, Attribute bgcolor ch c to ra vi tr s cyan khi price ca book ln hn 6. Mc ch ca ta l dng mu xanh da tri nht lm nn cho sch no c gi (price) cao hn 6. Di y l mt th d dng xsl:choose:
<xsl:for-each select="//book"> <div> <xsl:choose> <xsl:when test="self::*[genre = 'Romance']"> <xsl:attribute name="style">background-color: pink</xsl:attribute> </xsl:when> <xsl:when test="self::*[genre = 'Fantasy']"> <xsl:attribute name="style">background-color: lightblue</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="style">background-color: lightgreen</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:value-of select="title"/> </div>

</xsl:for-each>

Trong th d trn Attribute style ca Cascading Style Sheet s c nhng tr s cho backgroundcolor khc nhau ty theo loi sch. Nu l Romance th pink, Fantasy th lightblue, cn nu khng phi l Romance hay Fantasy (tc l xsl:otherwise) th lightgreen. Mu ny s c dng lm nn cho mc (title) ca sch. l cp Tags <xsl:choose>,</xsl:choose> c dng gi cc xsl:when, v xsl:otherwise bn trong. Sau y l listing ca mt catalog.xsl style sheet y , trong c c hai cch dng xsl:if v xsl:when ni trn:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Book Lovers' Catalog</TITLE> </HEAD> <BODY> <Center> <H1>Book Lovers' Catalog</H1> </Center> <TABLE Border="1" Cellpadding="5"> <TR> <TD align="center" bgcolor="silver"> <b>ID</b> </TD> <TD align="center" bgcolor="silver"> <b>Author</b> </TD> <TD align="center" bgcolor="silver"> <b>Title</b> </TD> <TD align="center" bgcolor="silver"> <b>Genre</b> </TD> <TD align="center" bgcolor="silver"> <b>Price</b> </TD> <TD align="center" bgcolor="silver"> <b>Published Date</b> </TD> <TD align="center" bgcolor="silver"> <b>Description</b> </TD> </TR> <xsl:for-each select="//book"> <TR> <TD> <xsl:value-of select="@id"/> </TD> <TD> <xsl:value-of select="author"/>

</TD> <TD> <xsl:choose> <xsl:when test="self::*[genre = 'Romance']"> <xsl:attribute name="style">background-color: pink</xsl:attribute> </xsl:when> <xsl:when test="self::*[genre = 'Fantasy']"> <xsl:attribute name="style">background-color: lightblue</xsl:attribute> </xsl:when> <xsl:otherwise> <xsl:attribute name="style">background-color: lightgreen</xsl:attribute> </xsl:otherwise> </xsl:choose> <xsl:value-of select="title"/> </TD> <TD> <xsl:value-of select="genre"/> </TD> <TD> <xsl:if test="price > 6"> <xsl:attribute name="bgcolor">cyan</xsl:attribute> </xsl:if> <xsl:value-of select="price"/> </TD> <TD> <xsl:value-of select="publish_date"/> </TD> <TD> <xsl:value-of select="description"/> </TD> </TR> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

Sau khi thm cu:


<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>

vo u h s catalog.xml, double click ln tn file catalog.xml, Internet Explorer s hin th kt qu sau:

Book Lovers' Catalog


ID Author Title Genre Price Published Date Description

bk102 Ralls, Kim

Midnight Rain

Fantasy

5.95

2000-1216

A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. A deep sea diver finds true love twenty thousand leagues beneath the sea. An anthology of horror stories about roaches, centipedes, scorpions and other insects. After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum. Microsoft's .NET initiative is explored in detail in this deep programmer's reference.

Thurman, bk107 Paula

Splish Splash

Romance

4.95

2000-1102

bk108

Knorr, Stefan

Creepy Crawlies

Horror

4.95

2000-1206

bk109

Kress, Peter

Paradox Lost

Science Fiction

6.95

2000-1102

bk110

O'Brien, Tim

Microsoft .NET: The Programming Bible

Computer

36.95

2000-1209

Bn c th ti v catalog.xml v catalog.xsl ti y.

Dng nhiu Templates trong mt Style Sheet


Trong bi trc, trong mi XSL Style Sheet ta thy vn vn ch c mt Template (bng km in), v n c p dng vo Root Element ca ti liu XML. Tht ra, XSL cng cho php ta dng nhiu Templates trong mt Style Sheet. C th bn cn lm vic y v hai l do. Th nht, bn c th phn chia cch trnh by ra tng phn ca ti liu XML, d debug hay sa i b phn no ca Style sheet. Th hai, bn c th dng XPath expressions p dng kiu trnh by no vo loi d liu no ty theo tr s ca n.

Khi mt Style Sheet cha nhiu templates, bn ch nh vic p dng ca chng vo lun l trnh by (presentation logic) bng cch dng lnh apply-templates. Thng thng, bn to mt Template cho Root Element ni l ch bin c ti liu v dng lnh apply-templates ch bin nhng Element nm bn trong ci top-level template y. Nhng Templates ny c th c gi lc no cn, v ci top-level template s x l mi d liu khng c Template no nhc ti. Tc l nu Element no khng c template p dng cho n th ta dng ci template tng qut ca Root Element. Th d nh ci Style Sheet sau y gm c: mt top-level template p dng vo Document (Root) Element, mt template cho nhng Element Product vi Attribute UnitPrice c tr s ln hn 70, mt template cho nhng Element Product khc, v mt template cho nhng Element Quantity:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: <xsl:value-of select="Order/@OrderNo"/> </P> <P>Date: <xsl:value-of select="Order/OrderDate"/> </P> <P>Customer: <xsl:value-of select="Order/Customer"/> </P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD> </TR> <xsl:for-each select="Order/Item"> <TR> <xsl:apply-templates></xsl:apply-templates> </TR> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> <xsl:template match="Product[@UnitPrice > 70]"> <TD> <xsl:value-of select="@ProductID"/> </TD>

<TD> <A> <xsl:attribute name="HREF">Products.asp?ProductID= <xsl:value-of select="@ProductID"/> </xsl:attribute> <xsl:value-of select="."/> </A> </TD> <TD> <FONT color="red"> <xsl:value-of select="@UnitPrice"/> </FONT> </TD> </xsl:template> <xsl:template match="Product"> <TD> <xsl:value-of select="@ProductID"/> </TD> <TD> <A> <xsl:attribute name="HREF">Products.asp?ProductID= <xsl:value-of select="@ProductID"/> </xsl:attribute> <xsl:value-of select="."/> </A> </TD> <TD> <xsl:value-of select="@UnitPrice"/> </TD> </xsl:template> <xsl:template match="Quantity"> <TD> <xsl:value-of select="."/> </TD> </xsl:template> </xsl:stylesheet>

Khi p dng Style Sheet ny vo ci ti liu t hng XML, ta s c h s HTML sau y:


<HTML> <HEAD> <TITLE>Northwind Home Page</TITLE> </HEAD> <BODY> <P>Customer Order</P> <P>Order No: 1047</P> <P>Date: 2002-03-26</P> <P>Customer: John Costello</P> <TABLE Border="0"> <TR> <TD>ProductID</TD> <TD>Product Name</TD> <TD>Price</TD> <TD>Quantity Ordered</TD>

</TR> <TR> <TD>1</TD> <TD> <A HREF="Products.asp?ProductID=1">Chair</A> </TD> <TD>70</TD> <TD>6</TD> </TR> <TR> <TD>2</TD> <TD> <A HREF="Products.asp?ProductID=2">Desk</A> </TD> <TD><FONT color="red">250</FONT></TD> <TD>1</TD> </TR> </TABLE> </BODY> </HTML>

Phn BODY ca HTML trn hin th nh sau:

Customer Order Order No: 1047 Date: 2002-03-26 Customer: John Costello
ProductID Product Name Price Quantity Ordered 1 2 Chair Desk 70 6

250 1

Cch p dng Style Sheet vo ti liu XML


Trc khi tip tc hc thm cc lnh khc ca XSL Style Sheet, ta cn hiu v bit cch p dng mt Style Sheet vo mt ti liu XML. p dng mt Style Sheet l mt chc nng ca mt XML parser nh MSXML ca Internet Explorer. Bn c th bo mt XML parser p dng mt Style Sheet vo mt XML bng cch

hoc l ch cn nht mt processing instruction vo u h s XML, hoc l vit mt vi dng code.

Dng XML parser hin th


Nu ta lu tr XSL Style Sheet ca h s t hng trong mt file tn Order.xsl th ta c th thm mt hng processing instruction xml-stylesheet vo u h s t hng XML nh sau:
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="Order.xsl"?> <Order OrderNo="1047"> <OrderDate>2002-03-26</OrderDate> <Customer>John Costello</Customer> <Item> <Product ProductID="1" UnitPrice="70">Chair</Product> <Quantity>6</Quantity> </Item> <Item> <Product ProductID="2" UnitPrice="250">Desk</Product> <Quantity>1</Quantity> </Item> </Order>

Khi mt XML parser c h s XML ny, ci processing instruction xml-stylesheet bo parser p dng h s style sheet Order.xsl transform XML. Attribute type cho bit loi style sheet c p dng, hoc l XSL style sheet hoc l cascading style sheet (CSS), mt loi style sheet dng ch nh mu v kiu ch. y n l XSL style sheet trong dng text. Attribute href cho bit tn ca file dng lm Style Sheet, path ca tn file y c th l tng i hay tuyt i. y filename ca style sheet l Order.xsl, khng c path, nn c ngha l n nm trong cng mt folder vi Order.xml. Nu ta dng mt chng trnh trnh duyt nh Internet Explorer 5.5 hay 6.0 n s t ng load Style Sheet thm dng iu cho ti liu XML. Trong lc Internet Explorer hin th kt qu, nu bn dng Menu Command View | Source ca browser, bn s ch thy code ca XML, ch khng thy code HTML nh bn on. Mun xem c code HTML, l kt qu ca vic transform XML bng cch p dng XSL bn cn ti v chng trnh cng c gi l Internet Explorer XML/XSL Viewer Tools t Microsoft Downloads. Sau khi Unzip file va ti v, bn right click tn ca hai files msxmlval.inf v msxmlvw.inf ri chn install ci chng lm Add-ins (nhng thnh phn thm chc nng vo mt chng trnh c sn) vo chng trnh Internet Explorer nh trong hnh di y.

By gi mun xem code HTML, bn right click ln trang Web trong IE ri chn command View XSLOutput t PopUpMenu nh trong hnh di y:

Dng code transform vi XSL


Cch dng mt ngn ng lp trnh bo mt XML parser ch bin mt ti liu XML s ty thuc vo hon cnh. Nu bn dng Microsoft XML parser, mt component tn MSXML, trong lp trnh th ti liu XML s c loaded vo trong mt Document Object Model (XMLDom) object. K bn c th gi method transformNode p dng mt XSL style sheet c loaded trc vo mt XMLDom object khc ch bin XML. Nh trong th d di y, ta dng hai DOM, mt ci load file Order.xml, mt ci khc load Order.xsl trong VBScript chy trn Active Server Pages (ASP):
Dim objXML ' DOM for XML Dim objXSL ' DOM for XSL Dim strResult ' Resultant document 'Load the XML document. Set objXML = CreateObject("Microsoft.XMLDom") objXML.Async = False objXML.Load "c:\Order.xml" 'Load the XSL style sheet. Set objXSL = CreateObject("Microsoft.XMLDom") objXSL.Async = False objXSL.Load "c:\Order.xsl" 'Apply the style sheet to XML strResult = objXML.transformNode(objXSL)

Sau khi chy on code trn, strResult s cha h s kt qu. Hnh di y minh ha vai tr ca XSLT processor trong cng tc transform mt h s XML da vo mt XSLT (t gi tr i ta c th dng t XSLT th cho XSL cng c) file:

Ta cng c th code bng JavaScript chy trong Browser, thay v trong WebServer, nh cho thy trong trang Web di y. N cng cho ra cng mt kt qu nh khi dng IE hin th XML trc tip.
<HTML> <HEAD> <TITLE>sample</TITLE> <SCRIPT language="javascript"> function init() { var srcDOM = new ActiveXObject("Msxml2.DOMDocument.4.0"); srcDOM.async=false; srcDOM.load("order.xml"); var xsltDOM= new ActiveXObject("Msxml2.DOMDOCUMENT.4.0"); xsltDOM.async = false; xsltDOM.load("order.xsl"); resDOM.innerHTML = srcDOM.transformNode(xsltDOM); } </SCRIPT> </HEAD> <BODY onload="init()"> <div id="resDOM"></div>

</BODY> </HTML>

C l bn hi ti sao ta khng dng thng XML nh pha trn hin th trang Web. Lu l ta c th dng k thut ny Transform mt XML vi XSL ri hin th n bn trong mt DIV, tc l mt vng gii hn bn trong trang Web, ch khng chim c trang Web. Ti y khi trang Web bt u load (onload event), IE gi function init() transform XML ri assign kt qu vo property innerHTML ca DIV resDOM. C mt method khc ta cng c th dng thay cho transformNode l transformNodeToObject. S khc bit chnh gia hai methods ny l:

transformNode: Kt qu ca method ny l mt tree di dng text string, in hnh l mt h s HTML. Ta c th cho n hin th trong mt browser hay lu tr vo mt file. transformNodeToObject: Kt qu ca method ny c vo trong mt object khc, ri chnh object y c th s c ch bin thm.

Khi ta dng mt trong hai method ni trn, tht ra object ngun (source object) khng cn phi l mt h s y . N c th ch l mt Node ca h s XML. Nu n ch l mt Node th ci XSLT processor xem tp hp Node y, v cc Nodes con chu ca n nh mt h s y . Tng t nh vy, mt object XSL c th l mt file XSL y , hay ch l mt Node bn trong mt file XSL. Bn c th ti v order.xml, order.xsl v trang Web c JavaScript ti y.

Anda mungkin juga menyukai