Professional Documents
Culture Documents
XMLTieng Viet
XMLTieng Viet
XML document
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.
Page 2
XML document
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>
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 wellformed 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 well-formed v n khng c mt top level Element:
Page 3
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 well-formed 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>
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> Page 4
XML document <Category CategoryName="Beverages"> <Product ProductID="1"> Coca-Cola </Category> </Product> </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>
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"?> Page 5
XML document <!-- 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> Page 6
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 ' & > Description du apostrophe du ampersand du ln hn
Page 7
XML document
du nh hn < du ngoc kp " Trong bi ti ta s hc v cch process (ch bin) mt ti liu XML.
Page 8
XML document
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
i ra nhnh ca Tree, ta s tm c node Customer bng cch dng XPath expression sau:
/child::Order/child::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:
Page 9
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
Tng t nh vy, ly ra Attribute ProductID ca Element con Product, ci location path tng i l:
child::Product/attribute::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
Page 10
XML document
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 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]
Page 11
XML document
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] 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, ng c .v.v., do ancestor:: axis lun lun k c root node tr khi chnh context node l root node. Chnh context node v t tin ca n. Ci ancestor-or-self:: axis lun lun k c root node. Cc Attributes ca context node. Nu context node khng phi l mt Element th chc chn axis s trng rng. Con ci ca context node. Mt con l bt c node no nm ngay di context node trong tree. Tuy nhin, Attribute hay Namespace nodes khng c xem l con ci ca context node. Con chu ca context node. Con chu l con, chu, cht, .v.v., do descendant:: axis khng bao gi cha Attribute hay Namespace nodes. Mi nodes hin ra sau context node trn tree, khng k con chu, Attribute nodes, hay Namespace nodes. Mi nodes em (nm sau) context node. following-sibling:: axis ni n ch nhng Nodes con, ca cng mt Node cha, nm trn tree sau context node. Axis khng k cc Nodes anh nm trc context node. Nu context node l Attribute hay Namespace th following-sibling:: axis s trng rng. Nhng Namespace nodes ca context node. Mi namespace c mt namespace node trong scope (phm vi hot ng) ca context node. Nu context node khng phi l mt Element th Axis s trng rng. Node cha ca context node, nu n c cha. Node cha l node nm ngay pha trn context node trn tree. Mi nodes hin ra trc context node trn tree, khng k cc nodes t tin, Attribute nodes, hay Namespace nodes.
Page 12
ancestor-or-self:: attribute::
child::
descendant::
following:: following-sibling::
namespace::
parent::
preceding::
XML document
preceding-sibling::
Mt cch nhn din preceding:: axis l mi nodes kt thc hon ton trc khi context node bt u. Mi nodes anh (nm trc) context node. preceding-sibling:: axis ni n ch nhng Nodes con, ca cng mt Node cha, nm trn tree trc context node. Nu context node l Attribute hay Namespace th preceding-sibling:: axis s trng rng. L chnh context node.
self::
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 book[excerpt]/author[degree] book[author/degree] book[excerpt][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"] author[lastname[1] = "Smith"] author/degree[@from != "Harvard"] ngha Mi Element author c cha t nht mt Element lastname vi tr s bng Smith. Mi Element author c Element lastname con u tin vi tr s bng Smith. Mi Element degree, l con mt Element author, v c mt Attribute from vi tr s khng phi l "Harvard".
Page 13
ngha Mi Element book c cha t nht mt Element excerpt. Mi Element title nm trong nhng Element book c cha t nht mt Element excerpt. Mi Element author c cha t nht mt Element degree v nm trong nhng Elements book c cha t nht mt Element excerpt. Mi Element book c cha t nht mt Element author vi t nht mt Element degree con. Mi Element book c cha t nht mt Element excerpt v t nht mt Element title.
XML document
Mi Element author c cha mt Element lastname bng vi Element lastname l con ca root Element editor. Mi Element author c tr s string l John Hamilton.
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 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 NodeType 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() node() processing-instruction() text() Tr v mi comment node. mi node. mi processing instruction node. mi text node. Th d following::comment() chn mi comment nodes hin ra sau context node. preceding::node() chn mi nodes hin ra trc context node. self::processing instruction() chn mi processing instruction nodes trong context node. child::text() chn mi text nodes l con ca the context node. ngha Mi Element firstname v lastname trong current context. Mi Element book hay magazine l con mt Element bookstore. Mi Element book hay Element author l con nhng Elements book. Mi Element price l con ca Element book hay Element magazine.
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")
ngha Mi Element author trong current context. Expresion ny tng ng vi expression trong hng k. Mi Element author trong current context.
XML document
/bookstore //author book[/bookstore/@specialty = @style] author/firstname bookstore//title bookstore/*/title bookstore//book/excerpt//emph .//title author/* book/*/lastname */* *[@specialty] @style price/@exchange price/@exchange/total
book[@style]
book/@style
Document (Root) Element tn bookstore ca ti liu ny. Mi Element author trong ti liu. Mi Element book c Attribute style vi value bng value ca Attribute specialty ca Document Element bookstore ca ti liu. Mi Element firstname con ca cc Elements author. Mi Element title mt hay nhiu bc thp hn, tc l con chu ca, Element bookstore. Lu l expression ny khc vi expression trong hng k. Mi Element title chu ca cc bookstore. Mi Element emph bt c ni no di excerpt l con ca nhng elements book , bt c ni no di element bookstore. Mi Element title mt hay nhiu bc thp hn current context node. 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 current context, tc l nhng Elements price ca current context node. Tr v mt node set trng rng, v Attributes khng c Element con. Expression ny c chp nhn trong vn phm ca XML Path Language, nhng khng tht s hp l. Mi Element book c Attribute style trong current context node. Lu phn nm trong ngoc vung l iu kin ca Element book Attribute style ca mi Element booktrong current context node. y khng c iu kin nh hng trn. Ta ni n Attribute hay Element nm bn phi nht. Mi Attributes ca current context node. Element author th nht trong current context node. Element author th ba c mt Element con firstname. Element book t namespace my. Mi Element trong namespace my.
XML document
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>
Page 16
XML document
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
Page 17
XML document
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"/> Page 18
XML document </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:foreach>) . 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>
Page 19
XML document
Order No: 1047 Date: 2002-03-26 Customer: John Costello ProductID Product Name Price Quantity Ordered 1 Chair 70 6 2 Desk 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> Page 20
XML document <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>
Phn BODY ca HTML trn hin th nh sau: Customer Order Order No: 1047
Page 21
XML document
Date: 2002-03-26 Customer: John Costello ProductID Product Name Price Quantity Ordered 1 Chair 70 6 2 Desk 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.
XML document March 27, 2008 <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']"> Page 23
XML document
March 27, 2008 <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 background-color 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"/> Page 24
XML document </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>
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
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
bk107 Thurman,
Splish Splash
Romance
4.95
2000-11-
Page 25
XML document
Paula
02
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.
Creepy Crawlies
Horror
4.95
2000-1206
bk109
Kress, Peter
Paradox Lost
Science Fiction
6.95
2000-1102
Computer
2000-1236.95 09
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> Page 26
XML document <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> Page 27
XML document <xsl:template match="Quantity"> <TD> <xsl:value-of select="."/> </TD> </xsl:template> </xsl:stylesheet>
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
Page 28
XML document
1 2
Chair Desk
70 250
6 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
Page 29
XML document
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:
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:
Page 31
XML document
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.
Page 32
XML document
C c source code ca XML parser ca mnh bn s chim u th so vi ngi khc khi thit k hay deploy program trn mng. Trc khi bn v program ny ta hy n li cc qui lut cn bn v mt Well-Formed XML. Well-Formed XML Mc d bn c th t ra bao nhiu Tag cng c, nhng mi trang XML cn phi theo mt s qui lut c xem l Well-Formed (c u, c ui). Nu mt trang XML khng Well-Formed th coi nh xi khng uc, khng c chng trnh x l no s chu lm vic vi d liu bn trong ca n. Do mt trang XML cn phi theo ng cc qui lut sau y: 1. Trang XML phi bt u bng cu tuyn b XML (XML declaration). im ny ta c th b qua uc. 2. Mi b phn, gi l "element" phi nm gia mt Tag Pair. 3. Nu Tag no khng cha g gia th phi chm dt bng "/>", th d nh <BR/> hay <HR/>. 4. Mt trang XML phi c mt element c nht cha tt c cc elements khc. l root ca tree biu din trang XML. 5. Cc Tag Pair khng c xen k nhau (th d nh <name>John Stanmore<address>25 King Street</name></address> l bt hp l v <address> nm trong Tag Pair name). v thm mt vi qui lut v cch dng cc mu t c bit. Ngoi ra cc Tag Pair phi nh vn ng y nh nhau k c ch hoa, ch thng, (th d: <STUDENT> v </Student> l bt hp l) v tt c gi tr cc Attributes u phi nm gia hai ngoc kp (th d: standalone=yes l bt hp l, phi dng standalone="yes" mi c.) Thit k SXMLParser C mt VB6 class chnh lo hu nh hon ton vic parsing mt XML file. Sau khi instantiated mt Object thuc Class clsXMLParser, ta ch cn cho n tn ca XML file l n bt u cng tc parsing ngay. Nh trong hnh mu ca XML pha trn ta thy phn chnh ca XML l t hng th t tr i khi bt u vi Open Tag <library>. Tng ng vi mi Open Tag l c mt Close Tag, th d nh </library>. Bn trong mi cp Tags c th c nhng cp Tags (con) khc. Mt Open Tag c th cha nhiu cp Attributes di dng Name="Value". Lu l Value phi nm gia hai du ngoc. SXMLParser s i qua tng character mt ca XML file. Khi c xong mt Open Tag, th d nh: <book hardback="yes" series="Professional C++">
Page 33
XML document
SXMLParser s Raise mt StartElement Event c handled trong Form chnh bi Sub XMLParser_StartElement. Event ny cho Form chnh tn ca Tag v mt collection ca cc cp Name="Value" Attributes, th d nh Tag book u tin cha hardback="yes" series="Professional C++", chng hn. Trong Sub XMLParser_StartElement ta lm cng mt lc ba chuyn: 1. Lm p XML code, tc l cc hng tht ra, thc vo ty theo th bc cho d c. 2. Thm mu cho HTML file hin th XML code trong WebBrowser 3. To cc Nodes trong TreeView
Private Sub XMLParser_StartElement(ByVal Name As String, ByVal tagAttributes As clsAttributes) ' A complete Start Element has been processed Dim TStr ' Build a string of Atributes' Name="Value" pairs TStr = BuildAttributeString(tagAttributes) ' Display Name Tag in Pretty XML Listbox lstXML.AddItem Space(XMLParser.NestedLevel * TabWidth) & "<" & Name & TStr & ">" ' Add blue color to the equal sign TStr = Replace(TStr, "=", "=") ' prepare colour HTML Name tag lstHTML.AddItem Space(XMLParser.NestedLevel * TabWidth) & "<Font color=red><</Font>" _ & "<Font color=blue>" & Name & "" & "<Font color=green>" & TStr & "</Font>" & "<Font color=red>></Font>" ' add a node to the Treeview and save its index in the stack of nested nodes If XMLParser.NestedLevel = 0 Then ' create the root node With XMLTree.Nodes.Add(, , , Name) nodeStack(0) = .Index ' save the node index in stack .Expanded = True ' Expand node End With Else ' create a child node of the higher nested level mode With XMLTree.Nodes.Add(nodeStack(XMLParser.NestedLevel - 1), tvwChild, , Name) nodeStack(XMLParser.NestedLevel) = .Index ' save the node index in stack .Expanded = True ' Expand node End With End If End Sub
ti to hng Name="Value" cho collection ca cc Attributes ca mt Tag ta dng Function BuildAttributeString nh sau:
Function BuildAttributeString(ByVal tagAttributes As clsAttributes) As String ' Build a string of Atributes' Name="Value" pairs for Element or Instruction Dim i, TStr Dim attr As clsAttributeItem ' Iterate through each Attribute in the collection For i = 1 To tagAttributes.Count ' refer to i-th attribute Set attr = tagAttributes.Item(i) ' Start with a space, create string Name="Value" TStr = TStr & " " & attr.Name & "=""" & attr.Value & """" Next BuildAttributeString = TStr ' Return the resultant string End Function
XML document March 27, 2008 Event StartDocument() ' End of parsing Event EndDocument() ' An XML Instruction has been parsed Event ProcessingInstruction(ByVal Name As String, ByVal tagAttributes As clsAttributes) ' An XML comment has been parsed Event Comment(ByVal Text As String) ' An open tag as been parsed Event StartElement(ByVal Name As String, ByVal tagAttributes As clsAttributes) ' A close tag as been parsed Event EndElement(ByVal Name As String) ' A block of text has been parsed Event Characters(ByVal Text As String) ' Error encountered while parsing Event ParseError(ByVal ErrorNo As Integer, ByVal Description As String)
Trong khi parsing SXMLParser thay i State hay Mode ty theo trng thi n ang tm kim th g, chng hn nh character <, >, Attribute Name, Attribute Value, Close Tag .v.v.. Nu n khm ph l XML khng WellFormed th n s Raise mt ParseError Event vi l do v chi tit lin h v Error y hin th trong Form chnh, gip User bit cn sa i u trong XML file. Danh sch cc loi Error m SXMLParser support uc lit k di y. Xin lu l c khi Error Message khng r rng nh ta tng tng v parser khng thng minh nh chng ta.
Const Const Const Const Const Const Const Const Const Const Const Const Const cParseEmptyXML = 1 cParseNoCommentCloseTag = 2 cParseNoValueCloseQuote = 3 cParseNoAttributeName = 4 cParseNoEqualSign = 5 cParseNoAttributeValue = 6 cParseNoCDataCloseTag = 7 cParseUnknownSymbols = 8 cParseNoOpenQuote = 9 cParseBadOpenTag = 10 cParseBadCloseTag = 11 cParseMismatchTagName = 12 cParseNoInstructionCloseTag = 13
V cc Tag Pairs cn phi c Tag Names ging nhau hon ton (ch hoa, ch thng) v khng xen k nhau uc, nn ta cn c mt Stack cha cc Tag Names theo ng ng cp trn di. Mt Stack l mt danh sch theo th t Last-In, First-Out, tc l ci g mi vo nht s ra u tin. Ta thc hin Stack ny bng Class clsStack. clsStack cha cc Items thnh mt String, m cc Items uc ngn cch nhau bi mt vbNullChar (character c ASC value bng 0). Item mi nht (Last-In) nm u bn tri ca String. C ba Functions chnh ca Class clsStack l Push ( nht mt TagName vo), Pop ( ly TagName mi nht ra) v LastIn ( ch xem TagName mi nht, ch khng ly ra).
Public Sub Push(InItem As String) ' Push a Item up the Stack. ' Remove any vbNullChars in the Item ' Use vbNullChar as the Delimiter ' ' Prefix the Item to the Stack string mStacks = Replace(InItem, vbNullChar, "") & vbNullChar & mStacks mCount = mCount + 1 ' Increment the Item count End Sub
Page 35
XML document March 27, 2008 Public Function Pop() As String ' Remove and return the LastIn Item in the Stack. Dim Pos If mCount > 0 Then Pos = InStr(mStacks, vbNullChar) ' Locate vbNullChar If Pos > 0 Then Pop = Left(mStacks, Pos - 1) ' Extract the LastIn Item mStacks = Mid(mStacks, Pos + 1) ' Keep the remain of the Stack string mCount = mCount - 1 ' decrement the Item Count End If End If End Function Public Function LastIn() As String ' View the LastIn Item in the Stack. Leave Stack unchanged Dim Pos If mCount > 0 Then Pos = InStr(mStacks, vbNullChar) ' Locate vbNullChar If Pos > 0 Then LastIn = Left(mStacks, Pos - 1) ' Extract the LastIn Item End If End If End Function
Bn c th download chng trnh mu SXMLParser.zip c bit trong program ny, ch cn mt click duy nht ln nt Paste, XML text trong Clipboard s c bin thnh HTML code lm p v hin th XML code vi mu trong WebBrowser. Ngay sau bn c th Paste content ca Clipboard vo mt trang Web. Di y l listing ca Sub CmdPaste_Click
Private Sub CmdPaste_Click() ' Parse the Clipboard content and copy the resultant colour HTML back to clipboard Dim i, TStr ' Fetch content of clipboard TStr = Clipboard.GetText(vbCFText) ' Write it temporarily to "Temp.XML" file in the same folder where this program resides WriteTextFile GetLocalDirectory & "Temp.XML", TStr ' Place the XML filename into TextBox txtFilename txtFilename.Text = GetLocalDirectory & "Temp.XML" ' Emulating User's action of clicking the commandbutton Parse cmdParse_Click ' If there're something as a result, copy everything from the Listbox lstHTML ' except for the first and last line, which contain HTML header/footer. ' Select the required lines from the Textbox If lstHTML.ListCount > 2 Then For i = 1 To lstHTML.ListCount - 2 lstHTML.Selected(i) = True Next ' Emulating User's action of clicking the commandbutton Copy CmdCopy_Click End If End Sub
Page 36
XML document
K t ActiveX Data Objects version 2.1 (ADO 2.1) tr i, Microsoft ADO engine c th cho ta XML file di dng Microsoft XML - Data Schema format, cn uc gi l XML Reduced Data Schema, hay n gin hn l Reduced Data. XML Reduced Data Schema ni r datatypes v nhng tnh cht tng t ca schema (tc l default values, tin tc v primary key, .v.v..) t database v tin tc ny trong phn u ca XML file. Phn sau ca XML cha data trong dng nhng rows. Mt khi c ADO recordset ri, bn c th lu tr (save) data vo mt XML file bng cch dng Function Save ca recordset. ADO 2.1 ch cho ta save data vo mt XML file. Nhng ADO 2.5 cho ta convert recordset thnh stream format. Nu argument th nht ca Function Save l mt URL th Save cho ra data di dng intrinsic binary format. Tuy nhin, nu ta cho thm argument th nh l adPersistXML flag th stream c i thnh mt XML stream. Nu bn cha h nghe qua danh t stream trc y, hy th tng tng chuyn ny. C hai cch li bun da hu giao hng. Cch th nht h khing da hu t di ghe ln b, cht thnh mt ni nh trn sn mt chc sau bn hng cho ngi n chuyn ch i. Cch th hai, bn hng li xe n cp st b sng, mt li bun ng di ghe nm tng tri da hu ln cho mt bn hng ng trn xe chp ri chuyn qua cho ngi khc sp ln xe ny hay thy qua xe khc nu mun phn loi da hu ln nh. Cch giao hng th nht ging nh save data vo mt file. Trong cch giao hng th hai, nhng tri da hu c nm lin tc bay ln b ging nh mt dng nc bn i, ngha en ca ch stream l dng nc. Khi data c chuyn i di dng mt stream, u nhn c th x l data lp tc, v nhiu khi khng cn cha data na. Trong th d ny, va chp uc tri da ngi bn hng phi quyt nh ngay, nu da hu ln th ln xe ny, nu da hu nh hay nh qu th thy qua xe kia. Trong ADO 2.1, bn b bt buc phi output stream ra mt file, iu ny c khi ph th gi. Ci stream phi uc i ra Unicode formated text string, spool ra hard disk qua file interface. Ri nu bn cn XML, file y phi c loaded v parsed tr li ra XML stream. ADO 2.5 cho php bn vit thng kt qu vo mt XML DOM (Document Object Model) document, khi phi save ra file ri c v parse tr li. Chng trnh mu Bn c th download chng trnh mu ADOXML.zip xem cch save data t ADO ra XML. Bonus l phn load data t XML v save ngc li vo Access Database. chy chng trnh ADOXML bn cn Project | References hai libraries: Microsoft ActiveX Data Objects 2.5 Library v Microsoft Data Binding Collection.
ADO recordset dng y biu din data t table Publishers ca BIBLIO.MDB database. Kt qu l mt XML file gm c ba phn: Phn th nht: data gii thiu di dng attributes ca XML
Page 37
XML document March 27, 2008 <s:Schema id="RowsetSchema"> <s:ElementType name="row" content="eltOnly" rs:updatable="true"> <s:AttributeType name="PubID" rs:number="1" rs:maydefer="true" rs:basetable="Publishers" rs:basecolumn="PubID" rs:keycolumn="true"> <s:datatype dt:type="int" dt:maxLength="4" rs:precision="10" rs:fixedlength="true"></s:datatype> </s:AttributeType> <s:AttributeType name="Name" rs:number="2" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Name"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="50"></s:datatype> </s:AttributeType> <s:AttributeType name="c2" rs:name="Company Name" rs:number="3" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Company Name"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="255"></s:datatype> </s:AttributeType> <s:AttributeType name="Address" rs:number="4" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Address"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="50"></s:datatype> </s:AttributeType> <s:AttributeType name="City" rs:number="5" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="City"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="20"></s:datatype> </s:AttributeType> <s:AttributeType name="Fax" rs:number="6" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Fax"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="15"></s:datatype> </s:AttributeType> <s:AttributeType name="State" rs:number="7" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="State"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="10"></s:datatype> </s:AttributeType> <s:AttributeType name="Telephone" rs:number="8" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Telephone"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="15"></s:datatype> </s:AttributeType> <s:AttributeType name="Zip" rs:number="9" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Zip"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="15"></s:datatype> </s:AttributeType> <s:AttributeType name="Comments" rs:number="10" rs:nullable="true" rs:maydefer="true" rs:write="true" rs:basetable="Publishers" rs:basecolumn="Comments"> <s:datatype dt:type="string" rs:dbtype="str" dt:maxLength="1073741824" rs:long="true"></s:datatype> </s:AttributeType> <s:extends type="rs:rowbase"></s:extends> </s:ElementType> </s:Schema>
<rs:data> <z:row PubID="1" Name="SAMS" c2="SAMS" Address="11711 N. College Ave., Ste 140" City="Carmel" Fax=" " State="IN" Telephone=" " Zip="46032" Comments=" "></z:row> <z:row PubID="2" Name="PRENTICE HALL" c2="PRENTICE HALL" Address="15 Columbus Cir." City="New York" Fax=" " State="NY" Telephone="800-922-0579" Zip="10023" Comments=" "></z:row> <z:row PubID="3" Name="M & T" c2="M & T BOOKS" Address=" " City=" " Fax=" " State=" Page 38
XML document March 27, 2008 " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="4" Name="MIT" c2="MIT PR" Address="Long Island" City=" " Fax=" " State="N.Y." Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="5" Name="MACMILLAN COMPUTER" c2="MACMILLAN COMPUTER PUB" Address="11 W. 42nd St., 3rd flr." City="New York" Fax=" " State="NY" Telephone="212-869-7440" Zip="10036" Comments=" "></z:row> <z:row PubID="6" Name="HIGHTEXT PUBNS" c2="HIGHTEXT PUBNS" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="7" Name="SPRINGER VERLAG" c2="SPRINGER VERLAG" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="8" Name="O" REILLY=" c2=" O'REILLY=" Address=" 90=" City=" Cambridge'=" " State="MA" Telephone=" " Zip="02140" Comments=" "></z:row> <z:row PubID="9" Name="ADDISON-WESLEY" c2="ADDISON-WESLEY PUB CO" Address="Rte 128" City="Reading" Fax="617-964-9460" State="MA" Telephone="617-944-3700" Zip="01867" Comments=" "></z:row> <z:row PubID="10" Name="JOHN WILEY & SONS" c2="JOHN WILEY & SONS" Address="605 Third Ave" City="New York" Fax="212-850-6088 " State="NY" Telephone="212-850-6000" Zip="10158" Comments="DATABASES MICROCOMPUTER SOFTWARE PAPERBACK BOOKS - TRADE TEXTBOOKS - COLLEGE DICTIONARIES, ENCYCLOPEDIAS PERIODICALS PROFESSIONAL BOOKS SCIENCE (GENERAL) BUSINESS SOCIAL SCIENCES AND SOCIOLOGY COMPUTER SCIENCE, DATA PROCESSING ENGINEERING (GENERAL)"></z:row> <z:row PubID="11" Name="SINGULAR" c2="SINGULAR PUB GROUP" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="12" Name="Duke Press" c2="Duke Press" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="13" Name="Oxford University" c2="Oxford University Press" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="14" Name="Mit Press" c2="Mit Press" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="15" Name="CAMBRIDGE UNIV" c2="CAMBRIDGE UNIV PR" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="16" Name="Q E D" c2="Q E D PUB CO" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="17" Name="Cambridge University" c2="Cambridge University Press" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="18" Name="WORLD SCIENTIFIC" c2="WORLD SCIENTIFIC PUB CO" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="19" Name="IDG" c2="IDG BOOKS WORLDWIDE" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> <z:row PubID="20" Name="GOWER PUB" c2="GOWER PUB CO" Address=" " City=" " Fax=" " State=" " Telephone=" " Zip=" " Comments=" "></z:row> </rs:data> </xml>
XML document
c display, c lp vi XML, bng bt c WebBrowser no.Tht ra, ActiveX MSXML m ta dng cho VB6 l ca IE 5.5 khi ta Project | Reference "Microsoft XML, v3.0". Chng trnh mu Bn c th download chng trnh mu TransformXML.zip xem cch tho chng rt n gin.
Phn chnh ca chng trnh nm trong Sub Form_Load nh lit ra di y. Bn c th xem listing v gii thch v cch transform Library.xml da trn Library.xsl trong bi XML, K thut tin hc nng ct trong tng lai.
Private Sub Form_Load() Dim HTMLCode As String ' Need to Project | References "Microsoft XML, v3.0" to use DOM Dim myXMLDoc As New MSXML2.DOMDocument30 Dim myXSLDoc As New MSXML2.DOMDocument30 ' Need to Project | References "Microsoft Script Runtime" to use ' FileSystemObject and TextStream Dim Fs As FileSystemObject Dim TS As TextStream ' Display the XML file in a listbox PopulateListBoxFromFile LstXML, "Library.xml", False ' Display the XSL file in a listbox PopulateListBoxFromFile lstXSL, "Library.xsl", False ' Load the XML file myXMLDoc.Load App.Path & "\Library.xml" ' Load the XSL file myXSLDoc.Load App.Path & "\Library.xsl" ' Transform XML by XSL to give HTML HTMLCode = myXMLDoc.transformNode(myXSLDoc) ' Now Write the resultant HTML to file ' Create a FileSystem Object Set Fs = CreateObject("Scripting.FileSystemObject") ' Open TextStream for Output Set TS = Fs.OpenTextFile(App.Path & "\Library.htm", ForWriting, False, TristateUseDefault) TS.Write HTMLCode ' Write the whole HTML string in one stroke TS.Close ' Close the Text Stream Set Fs = Nothing ' Dispose FileSystem Object ' Display the HTML file in a listbox PopulateListBoxFromFile lstHTML, "Library.htm", False End Sub
Page 40
XML document
I nternet Explorer 5.0 cho ta Document Object Model (DOM) ActiveX gi l MSXML.DLL m ta c th dng trong VB6. u tin l Microsoft XML, version 2.0, tip theo l Microsoft XML, v2.6 v mi nht l Microsoft XML, v3.0. C ba DLL ny u c trong danh sch cc References m ta c th include khi dng IDE Menu command Project | References. Khi ta Load mt XML file vo DOM, n t ng parse XML data build mt Tree gm nhiu nodes vi th bc cha, con bn trong. Da theo ta c th display ci DOM Tree y trong mt TreeView c th hnh dung c cu trc ca XML data. Trong th d di y, ta Load mt XML file tn people.xml vo DOM. XML file ny cn c mt Data Type Definition file tn people.dtd. Khi DOM load XML file, ta c th dn n kim (validate) xem XML data c theo ng tiu chun i hi trong dtd file. Content ca people.xml nh sau, lu hng th hai nhc n people.dtd m DOM s dng validate data trong XML file:
<?xml version="1.0"?> <!DOCTYPE PEOPLE SYSTEM "people.dtd"> <PEOPLE> <PERSON PERSONID="p1"> <NAME>Peter Greenway</NAME> <ADDRESS>234 King St, Newtown, NSW, Australia</ADDRESS> <TEL>(612) 97463534</TEL> <FAX>(612) 97463535</FAX> <EMAIL>pgreenway@ozemail.com.au</EMAIL> </PERSON> <PERSON PERSONID="p2"> <NAME>Sue Williams</NAME> <ADDRESS>72/324 John St, Cabramatta, NSW, Australia</ADDRESS> <TEL>(612) 9745 2263</TEL> <FAX>(612) 9745 2264</FAX> <EMAIL>swilliams@bigpond.com.au</EMAIL> </PERSON> <PERSON PERSONID="p3"> <NAME>Helen Clark</NAME> <ADDRESS>74 GreenHill Rd, Wayville, SA, Australia</ADDRESS> <TEL>(618) 9756 3635</TEL> <FAX>(618) 9756 3636</FAX> <EMAIL>hclark@tgp.com.au</EMAIL> </PERSON> <PERSON PERSONID="p4"> <NAME>Martin Howard</NAME> <ADDRESS>652 Broadbeach Drive, St Kilda, Melbourne, Australia</ADDRESS> <TEL>(613) 9756 2312</TEL> <FAX>(613) 9756 2313</FAX> <EMAIL>mhoward@island.net.au</EMAIL> </PERSON> <PERSON PERSONID="p5"> <NAME>Pam Rose</NAME> <ADDRESS>24/274 Stancey St, Bankstown, NSW, Australia</ADDRESS> <TEL>(612) 9867 9821</TEL> <FAX>(612) 9867 9822</FAX> <EMAIL>prose@globalfreeway.com.au</EMAIL> </PERSON> <PERSON PERSONID="p6"> <NAME>Le Duc Hong</NAME> Page 41
XML document <ADDRESS>3 Rawson St, Epping, NSW,Australia</ADDRESS> <TEL>(612) 9783 1442</TEL> <FAX>(612) 9783 1445</FAX> <EMAIL>ldhong@dingoblue.com.au</EMAIL> </PERSON> <PERSON PERSONID="p7"> <NAME>u ch Xng</NAME> <ADDRESS>435 Trn Hng o, Vnh Long , Vit Nam</ADDRESS> <TEL>847 74847</TEL> <FAX>847 9682</FAX> <EMAIL>dixonau@vovisoft.com</EMAIL> </PERSON> <PERSON PERSONID="p8"> <NAME>L Phc Hiu</NAME> <ADDRESS>234 L Cng Un, Saigon, Vit Nam </ADDRESS> <TEL>827 3746</TEL> <FAX>827 4645</FAX> <EMAIL>lyhieu@vnn.vn</EMAIL> </PERSON> </PEOPLE>
Trong file people.dtd pha trn ta c: 1. Hng th nht ni rng ci root Node (Node gc) tn l PEOPLE. N c mt hay nhiu Nodes con tn PERSON. 2. Hng th nh ni mi Node PERSON c nhng Nodes con tn NAME, ADDRESS, TEL, FAX v EMAIL. 3. Cc hng cn li cho bit mi Node NAME, ADDRESS, TEL, FAX, EMAIL u cha text string. Vic u tin khi chy program l bn click nt Load XML into DOM and Display Tree. i mt cht xu, Tree ca XML s hin ra trong TreeView. ng thi XML data cng c displayed trong WebBrowser pha bn phi. Sau , mi ln bn click ln du+ hay - bn tri tn ca mt ngi trong TreeView, chi tit ca ngi s c display trong cc TextBox pha trn. Sau khi selected mt Person, bn c th Delete tn bng cch click nt Delete. Ngoi ra bn cng c th thm tn mt ngi bng cch click nt Clear to Add, in cc chi tit ca Person vo cc TextBoxes ri click Save new record. Mi ln bn Delete mt Person hay Add mt New Person, program t ng Save kt qu xung XML file. Hai TextBoxes txtName v txtAddress khng phi l TextBoxes thng thng nhng l TextBoxes ca ActiveX Form2. Cc Controls ca Form2 c th display ch Vit bng Unicode. Do nu bn Click ln tn L Phc Hiu chng hn, bn s thy tn v a ch c display trong Font Tahoma c du y ca ch Vit. Mun c cc Controls ca Form2 display ch Vit bn dng menu command Project | Components popup Components Dialog, k click Microsoft Forms 2.0 Object Library nh trong hnh di y:
Page 42
XML document
Bn c th download chng trnh mu DOMTree.zip chy th. bit thm cc Properties v Methods ca cc Classes trong MSXML, t trong VB6 IDE bn press F2 display Object Browser. Khi Object Browser Dialog hin ra, chn MSXML2 t ComboBox pha trn ang display <All Libraries>, k chn mt class, th d nh IXMLDOMElement t ListBox bn tri, chi tit ca selected Class s c displayed trong ListBox bn phi nh trong hnh di y:
Page 43
XML document
I nternet Explorer 5.0 cho ta Document Object Model (DOM) ActiveX gi l MSXML.DLL m ta c th dng trong VB6. u tin l Microsoft XML, version 2.0, tip theo l Microsoft XML, v2.6 v mi nht l Microsoft XML, v3.0. C ba DLL ny u c trong danh sch cc References m ta c th include khi dng IDE Menu command Project | References. Khi ta Load mt XML file vo DOM, n t ng parse XML data build mt Tree gm nhiu nodes vi th bc cha, con bn trong. Da theo ta c th display ci DOM Tree y trong mt TreeView c th hnh dung c cu trc ca XML data. Trong th d di y, ta Load mt XML file tn Library.xml vo DOM. XML file ny cn c mt Schema file tn LibrarySchema.xml. Khi DOM load XML file, ta c th dn n kim (validate) xem XML data c theo ng tiu chun i hi trong Schema file. Content ca Library.xml nh sau, lu hng th 7 nhc n LibrarySchema.xml m DOM s dng validate data trong XML file:
<?xml version="1.0"?> <?xml:stylesheet type="text/xsl" href="Library.xsl"?> <!-- Copyright 2000 Wattle Software http://XMLwriter.net/ --> <library xmlns="x-schema:LibrarySchema.xml"> <!-- declare the Schema which defines this document --> <name>Northmead Local Library</name> <book hardback="yes" availableforloan="no"> <title>C++ Programming for Beginners</title> <author> <first-name>Claude</first-name> <last-name>Schwartz</last-name> </author> <callno>005.133/C</callno> <online_url>http://library/online_books/005133C.html</online_url> </book> <journal series="XML Users Journal"> <title>XML Users Journal August 1999</title> <date>1999-08-01</date> <callno>005.133/C</callno> </journal> <video> <title>Titanic</title> <director> <name>James Cameron</name> </director> <callno>643.11/T</callno> </video> <book> <title>The C Programming Language</title> <author> <first-name>Brian</first-name> <last-name>Kernighan</last-name> </author> <author> <first-name>Dennis</first-name> <last-name>Ritchie</last-name> </author> <callno>005.133/C2</callno> Page 44
XML document March 27, 2008 </ElementType> <ElementType name="journal" content="eltOnly"> <!-- declare series as an optional attribute of journal --> <attribute type="series" required="no"></attribute> <element type="title"></element> <element type="date"></element> <element type="callno"></element> </ElementType> <ElementType name="book" content="eltOnly"> <!-- declare hardback as an optional attribute of journal with default value of "no" --> <attribute type="hardback" default="no"></attribute> <attribute type="availableforloan" default="yes"></attribute> <element type="title"></element> <!-- allow for multiple authors with maxOccurs --> <element type="author" maxOccurs="*"></element> <element type="callno"></element> <!-- allow for ONE optional URL --> <element type="online_url" minOccurs="0" maxOccurs="1"></element> </ElementType> <ElementType name="library" content="eltOnly"> <!-- the library name comes first --> <element type="name"></element> <!-- followed by a collection of books, videos and cds --> <group order="many"> <element type="book" maxOccurs="*"></element> <element type="journal" maxOccurs="*"></element> <element type="video" maxOccurs="*"></element> <element type="cd" maxOccurs="*"></element> </group> </ElementType> </Schema>
Vic u tin khi chy program l bn click nt Load XML and Display in TreeView. i mt cht xu, Tree ca XML s hin ra trong TreeView. ng thi Content ca XML file cng c loaded vo ListBox lstXMLSource v bn s thy n nu bn click Tab XML Source. D nhin bn c th display bt c mt XML file no nu bn n vo folder ca program v enter Filename ca n vo TextBox txtXMLFileName trc khi click nt Load XML and Display in TreeView.
Trong program ny ta dng Object IXMLDOMNode, thay v Object IXMLDOMElement ln lt i qua mi nodes ca XML DOM. Program gi Sub AddNode b cc Nodes vo TreeView. c bit l AddNode gi chnh n bn trong Sub AddNode. K thut ny gi l recursive, m ta thng ly dng trong nhng cu trc ging nh nhnh cy, khi chnh mt Con li c nhiu Con khc. Listing ca Sub AddNode nh sau:
Private Sub AddNode(ByRef oElem As IXMLDOMNode, Optional ByRef oTreeNode As Node) ' Add a Node to the TreeView Dim oNewNode As Node Page 46
XML document March 27, 2008 Dim oNodeList As IXMLDOMNodeList Dim i As Long ' Create the new node If oTreeNode Is Nothing Then ' Go through here when creating the top level nodes, i.e. childNodes of root node Set oNewNode = TreeView.Nodes.Add Else Set oNewNode = TreeView.Nodes.Add(oTreeNode, tvwChild) End If ' Expand TreeView node oNewNode.Expanded = True ' Prepare the Text for the TreeView Node If oElem.nodeType = NODE_ELEMENT Then ' Element Node type. Use Node name and Attribute values oNewNode.Text = BuildNodeLabel(oElem) ElseIf (oElem.nodeType = NODE_TEXT) Then ' Last Node in the branch. Use Text oNewNode.Text = oElem.Text ElseIf (oElem.nodeType = NODE_COMMENT) Then ' Comment Node. Display the comment oNewNode.Text = "Comment:" & oElem.Text Else ' Display Nodename as default oNewNode.Text = oElem.nodeName End If ' process the childNodes which form a NodeList Set oNodeList = oElem.childNodes ' Iterate through each childNode For i = 0 To oNodeList.length - 1 ' Recursively call AddNode to add more nodes as children of oNewNode, ' treating AddNode just like another Sub AddNode oNodeList.Item(i), oNewNode Next End Sub
C ba loi Nodes ta x l y: NODE_ELEMENT, NODE_TEXT v NODE_COMMENT. Element Node th c Node , Attributes v Con. Text Node v Comment Node th ch c text. Bn c th download chng trnh mu XMLTreeDOM.zip chy th. bit thm cc Properties v Methods ca cc Classes trong MSXML, t trong VB6 IDE bn press F2 display Object Browser. Khi Object Browser Dialog hin ra, chn MSXML2 t ComboBox pha trn ang display <All Libraries>, k chn mt class, th d nh IXMLDOMNode t ListBox bn tri, chi tit ca selected Class s c displayed trong ListBox bn phi nh trong hnh di y:
Page 47