Programming x Ml

Embed Size (px)

Citation preview

  • 8/13/2019 Programming x Ml

    1/65

    rogramming XML with C#

    Programming XML with C# is a book written in step-by-step tutorial format for beginners andstudents who want to learn XML programming using C# language. It is recommended that you

    ha e some programming e!perience using any of the ob"ect-oriented languages such as C $Pascal$ or %a a. It is also recommended that you are familiar with C# language synta!es andprogramming. If you are not a C# programmer$ I recommend to read Programming C# for &eginners before this book. 'his book can be found in C# Programming section of C# Corner.

    In this book$ you will learn the basic elements of XML and classes and ob"ects a ailable in .()'*ramework to work with XML. +fter that$ you will learn how to read$ write$ updated$ andtransform XML using C#. .()' also pro ides support for relationships between data , ia+ .()'/ and XML. In this chapter$ I also discuss how you can take ad antages of classesfound on + .()' and connect data with XML.

    http://www.c-sharpcorner.com/UploadFile/mahesh/csp08202007084545AM/csp.aspxhttp://www.c-sharpcorner.com/UploadFile/mahesh/csp08202007084545AM/csp.aspxhttp://www.c-sharpcorner.com/UploadFile/mahesh/csp08202007084545AM/csp.aspxhttp://www.c-sharpcorner.com/UploadFile/mahesh/csp08202007084545AM/csp.aspx
  • 8/13/2019 Programming x Ml

    2/65

    'able of Contents

    0. Introduction to XML1. M er iew2. XML 3epresentation in .()' 4orld5. 'he XML.()' +rchitecture6. 3eading XML7. 4riting XML8. 9nderstanding M Implementation:. 'ransformation and X;L'isual ;tudio .()'

  • 8/13/2019 Programming x Ml

    3/65

    Introduction to XML

    Note: If you are familiar with HTML and XML, you may skip this section and jump to XMLRepresentation in N!T "orld section

    The #$% N!T and XML N!T &ramework #pplication 'ro(rammin( Interface )#'I* com+inationpro ides a unified way to work with XML in the Microsoft N!T &ramework There are two ways torepresent data usin( XML: in a ta((ed-te.t format metalan(ua(e similar to HTML and in arelational ta+le format /ou use #$% N!T to access relational ta+le formats /ou would use$%M to access the te.t format

    0efore talkin( a+out the role of XML in the N!T &ramework and how to work with it, it1s importantyou understand the +asic +uildin( +locks of XML and its related terminolo(y /ou1ll learn the+asic definitions of 2tandard 3enerali4ed Markup Lan(ua(e )23ML* and HTML in the followin(sections If you1re already familiar with these lan(ua(es, you can skip to the 5XML % er iew6section

    ;tandard ?enerali@ed markup Language ,;?ML/

    In 789 , 2tandard 3enerali4ed Markup Lan(ua(e )23ML* +ecause the international standardsfor representin( electronic documents in a unified way 23ML pro ides a standard format fordesi(nin( your own markup schemes Markup is a way to represent some information a+outdata

    Later Hyperte.t Markup Lan(ua(e )HTML* +ecame the international standard for representin(documents on the "e+ in a unified way

    Hyper text Markup Language (HTML)

    The HTML file format is te.t format that contains, rather hea ily Markup ta(s # ta( is a sectionof a pro(ram that starts with ; and ends with < such as ; name < )#n element consists of a pair ofta(s, startin( with ; name < and endin( with ;= name

  • 8/13/2019 Programming x Ml

    4/65

    If you iew this field in a +rowser, you1ll see the te.t Here is the +ody part In Listin( -7, yourHTML file starts with the ta( and ends with the ta( The ta( tells a+rowser that this is the startin( point of an HTML document The ;=html< ta( tells a +rowser thatthis is the endin( point of an HTML documents These ta(s are re>uired in all HTML documentsThe $efines stron( te.t $efines a ta+le $efines a row of a ta+le $efines a cell of a ta+le row $efines a font name and si4e

    There are comes ta(s +eyond those descri+ed in ta+le -7 In fact the "A@1s HTML Bspecification is >uite e.tensi e Howe er, discussin( all of the HTML ta(s is +eyond the scope ofthis article 0efore mo in( to the ne.t topic, you1ll take a look at one more HTML e.ample usin(the ta(s discussed in the ta+le Listin( -D shows you another HTML document e.ample

    Listing 6-*. HTML tag t+eir usage

    ;html, which specifies the XML ersion

    The ne.t statement of a schema contains an .sd:schema statement, .mlns, and tar(etnamespace The .sd: schema indicates that file is a schema

    # schema starts with a < sd s hema> ta( and ends with a tag #ll schemaitems ha e the prefi. .sd The mlns =: http //))).) .org/G !/+MLs hema 6 is ahttp:==www "Ac or( RI, which indicates the schema should +e interpreted accordin( to thedefault, namespace of the "A@ The ne.t piece of this line is the tar(et namespace, whichindicates the location of a machine )a RI* Listin( - is a schema representation for thedocument in Listin( -J

    Listing 6-7. ,ML s2+ema example

    ;.sd:schema .mlns:.sd G http:==www wA or(=DCC7=XML 2chema < ml%stylesheet type= te t/ sl href = boo*s. sl >

    &tart an3 En3 tags

    2tart and end ta(s are the heart of XML lan(ua(e #s mentioned earlier in the article, XML isnothin( +ut a te.t file start and end ta(s !ach ta( starts with and ends with

  • 8/13/2019 Programming x Ml

    13/65

    you want to add a ta( called to your XML file, it must start with ;+ook< and end the, as shown in this e.ample:

    < ml 0ersion = !. > The A-tobiography of 2en3amin 4ran*lin

    2en3amin4ran*lin5.66

    NOTE: !mpty elements don1t ha e to heed this ;

    the parser will treat those characters as data #nother (ood e.ample of @$#T# is the followin( e.ample:

    This is the title of a page

    In this case, the parser will treat the second title as data as data, not as a mark up ta(

    "+ara2ter an3 entity re eren2e

    In some cases, you can1t use a character directly in a document +ecause of some limitations,such as character +ein( treated as markup character or a de ice or processor limitation

    0y usin( character and entity references, you can include information in a document +y referencerather than the character

    # character reference is a he.adecimal code for a character /ou use the hash sym+ol ) * +eforethe he.adecimal alue The XML parser takes care of the rest &or e.ample, the characterreference for the Return Uey is d.

    http://www.c-sharpcorner.com/xmlNethttp://www.c-sharpcorner.com/xmlNet
  • 8/13/2019 Programming x Ml

    14/65

    The reference start with an ampersand ) * and a , and it ends with a semicolon ) * The synta.for decimal and he.adecimal references is 0al-e and 0al-e respecti ely XML hassome +uilt-in entities se the It, (t, and amp entities for less than, (reater than, and ampersand,respecti ely Ta+le -D shows fi e XML +uilt-in entities and their references &or e.ample, if youwant to write a < + or Pack V Pill, you can do that +y usin( these entities:

    A gtNb and Oa * amp N Oill

    Ta!le 6-*. ,ML 8uil3- in Entities

    ENT T0 'E5E'EN"E %E&"' T ONLt lt Less than: ;9t gt 3reater than: uote: WA-ot -ot $ou+le >uote: 5

    Empty elements

    !mpty elements start and end with the same ta( They start with ; and end with < The te.t+etween these two sym+ols is the te.t data &or e.ample:

    uotes otherwise the parser will (i e an error Listin( -9 is ane.ample of an attri+ute in a ta( In the e.ample, the ta( has +order and widthattri+utes, and the ta( a width attri+ute

    Listing 6-9. Attri!utes in t+e ta!le; tag

    mailto:Jack@ampmailto:Jack@amp
  • 8/13/2019 Programming x Ml

    15/65

    Co)!, 7ol-mn!Co)!, 7ol-mnG

    Co)G, 7ol-mn!Co)G, 7ol-mnG

  • 8/13/2019 Programming x Ml

    16/65

    - M o er iew

    $ocument o+ject model )$%M* is a platform- and lan(ua(e- neutral interface that allowspro(rams and scripts to dynamically access and update XML and HTML documents The $%M

    #'I is a set of lan(ua(e- independent, implementation- neutral interfaces and o+jects +ased onthe %+ject Mana(ement 3roup )%M3* Interface $efinition Lan(ua(e )I$L* specification )not the@%M* ersion of I$L* 2et http:==www wA or(=TR=$%M-Le el-D= for more detail

    $%M defines the lo(ical structure of a document1s data /ou can access the document in astructured format )(enerally throu(h a tree format* Tree nodes and entities represent thedocument1s data $%M also helps de elopers +uild XML and HTML documents, as well as toadd, modify, delete, and na i(ate the document1s data &i(ure -D shows you arious contents of$%M in a tree structure

    5igure 6-*. %OM tree stru2ture

    This is the tree structure implementation of an XML file

    Mahesh Testing

    'e ond Line Tested

    &i(ure -A shows the $%M tree representation of this XML

    http://www.w3.org/TR/DOM-Level-2/http://www.w3.org/TR/DOM-Level-2/http://www.w3.org/TR/DOM-Level-2/
  • 8/13/2019 Programming x Ml

    17/65

    5igure 6-/. ,ML %OM tree representati#n

    In $%M, a document takes a hierarchical structure, which is similar to a tree structure Thedocument has a root node, and the rest of the document has +ranches and lea es

    These nodes are defines as interfaces o+ject /ou use the interfaces to access and manipulatedocument o+jects The $%M core #'I also allows you to create and populate documents loaddocuments and sa e them

    Ta+le -A defines some XML document nodes and node contents

    Ta!le 6-/. ,ML N#3es

    NO%E %E&"' T ON "H L%'EN$ocument Represent an HTML or XML

    document and root of the documenttree

    !lement,

    'rocessin(Instruction,$ocumentType, @omment$ocumentType Represent the document type

    attri+ute of a documentNo children

    !lement #n element of the document !lement, Te.t, @omment,'rocessin(Instruction,@$#T#2ection,!ntityReference

    #ttr #n attri+ute Te.t, !ntityReference'rocessin(Instruction Represent a processin( instruction

    used in XMLNo children

    @omment Represent comments in an XML orHTML document characters+etween the startin( ;E - - andendin( - - . 'ea3ing an ,ML ile

    +mlTe tCeader reader = ne) +mlTe tCeader @ "7 /boo*s.+ml" BN7onsole .RriteLine @ "9eneral &nformation" BN7onsole .RriteLine @ "= = = = = = = = = " BN7onsole .RriteLine@reader.;ameBN7onsole [email protected]&BN7onsole [email protected] al;ameBN

    $etting N#3e n #rmati#n

    The Name 'roperty returns the name of the node with the namespace prefi., and theLo al;ame property returns the name of the node without the prefi.

    The Item is the inde.er The alue property returns the alue of a current node you can e en (etthe le el of the node +y usin( the $epth property, as shown in this e.ample:

    +mlTe tCeader reader = ne) +mlTe tCeader @ "7 /boo*s.+ml" BN)hile @reader.Cead@BBUif @reader.HasSal-eB

  • 8/13/2019 Programming x Ml

    24/65

    U7onsole .RriteLine@ ";ame " V reader. ;ameBN7onsole .RriteLine@ ";ode epth " V reader. epth.To'tring@ BBN7onsole .RriteLine@ "Sal-e " V reader.Sal-eBNWWThe Node Type property returns the type of the current node in the form of +ml;odeTypeenumeration:

    +ml;odeType type = reader.;odeTypeN

    "hich defines the type of a node The +ml;odeType enumeration mem+ers are #ttri+ute,@$#T#, @omment, $ocument, !lement, "hite2pace, and so on These represent XMLdocument node types

    In Listin( -7C, you read a document1s nodes one +y one and count them %nce readin( andcountin( are done, you see how many comments, processin( instructions, @$#T#s, elements,whitespaces, and so on that a document has and display them on the console The+mlCeade r NodeType property returns the type of node in the form of +ml;odeTypeenumeration The +ml;odeType enumeration contains a mem+er correspondin( to each nodetypes /ou can compare the return alue with +ml;ode Type meme+ers to find out the type of anode

    Listing 6-1?. $etting n#3e in #rmati#n

    stati 0oid Main@ string K argsB Uint e 7o-nter = , P&7o-nter = , o 7o-nter = , 7omment7o-nter = Nint ?lement7o-nter = , Attrib-te7o-nter = , Te t7o-nter = ,Rhitespa e7o-nter = N+mlTe tCeader reader = ne) +mlTe tCeader @ "7 /boo*s.+ml" BN)hile @reader.Cead@BBU

    +ml;odeType nodetype = reader.;odeTypeN s)it h @nodetypeB U ase +ml;odeType .+ml e laration e 7o-nterVVN brea* N ase +ml;odeType .Pro essing&nstr- tion P&7o-nterVVN brea* N ase +ml;odeType . o -mentType o 7o-nterVVN brea* N ase +ml;odeType .7omment

    7omment7o-nterVVN brea* N ase +ml;odeType .?lement ?lement7o-nterVVN if @reader.HasAttrib-tesB Attrib-te7o-nter V= reader.Attrib-te7o-ntN brea* N ase +ml;odeType .Te t Te t7o-nterVVN brea* N

  • 8/13/2019 Programming x Ml

    25/65

    ase +ml;odeType .Rhitespa e Rhitespa e7o-nterVVN brea* N WW// print the info7onsole .RriteLine@ "Rhite 'pa es " V Rhitespa e7o-nter.To'tring@BBN7onsole .RriteLine@ "Pro ess &nstr- tion " V P&7o-nter.To'tring@BBN7onsole .RriteLine@ " e laration " V e 7o-nter.To'tring@BBN7onsole .RriteLine@ "Rhite 'pa es " V o 7o-nter.To'tring@BBN7onsole .RriteLine@ "7omments " V 7omment7o-nter.To'tring@BBN7onsole .RriteLine@ "Attrib-tes " V Attrib-te7o-nter.To'tring@BBNW

    The case statement can ha e alues +ml;odeType .+ml e laration,+ml;odeType .Pro essing&nstr- tion, +ml;odeType . o -mentType,+ml;odeType .7omment, +ml;odeType .?lement, +ml;odeType .Te t,+ml;odeType .Rhitespa e, and so on

    The +ml;odeType enumeration specifies the type of node Ta+le -B descri+es its mem+ers

    Ta!le 6- . t+e xml N#3e Type Enumerati#n@s mem!ers

    MEM8E' NAME %E&"' T ON #ttri+ute #ttri+ute node@$#T# @$#T# section@omment @omment node$ocument $ocument o+ject$ocument&ra(ment $ocument &ra(ment$ocumentType The $T$, indicated +y the ;E $%@T/'!< ta(!lement !lement node!nd!lement !nd of element!nd!ntity !nd of an entity

    !ntity !ntity declaration!ntityReference Reference to an entityNone Returned if +mlCeader is not called yetNotation Returned if +mlCeader is not called yet'rocessin(Instruction Represents a processin( instruction )'I* node2i(nification"hitespace Represents white space +etween markup in a mi.ed

    content modelTe.t Represent the te.t content of an element"hitespace Represents white space +etween markupXml$eclaration Represents an XML declaration node

    M# ing t# a "#ntent

    /ou can use the Mo0eToMethod to mo e from the current to the ne.t content node of an XMLdocument # content1s node is an item of the followin( type: te.t @$#T#, !lement,!ntityReference, or !ntity 2o if you call the Mo0eTo7onten t method, it skips other types ofnodes +esides the content type nodes &or e.ample if the ne.t node of the current node is$.l$eclaration, or $ocumentType, it will skip these nodes until it finds a content type node 2eethe followin( e.ample:

    +mlTe tCeader reader = ne) +mlTe tCeader @ " Xboo*s. ml" BN

  • 8/13/2019 Programming x Ml

    26/65

    if @reader.Cead@BBU7onsole .RriteLine@reader.;ameBNreader.Mo0eTo7ontent@BN7onsole .RriteLine@reader.;ameBNW

    T+e $et Attri!utes # a N#3e

    The 9etAttrib-te method is an o erloaded method /ou can use this method to returnattri+utes with the specified name, inde., local name, or namespace RI /ou use theHasAttrib-tes property to check if a node has attri+utes, and Attrib-tes7o-nt returns thenum+er of attri+utes on the node The local name is the name of the current node withoutprefi.es &or e.ample, if represents a name of a node, where +k is a namespaceand: is used to refer to the namespace, the local name for the element is +ookMo0eTo4irstAttrib-tes mo es to the first attri+ute The Mo0eTo?lement method mo es tothe element that contains the current attri+utes node )see listin( -77*

    Listing 6-11. $et Attri!utes # a n#3e

    -sing 'ystemN-sing 'ystem.+mlN

    lass +mlCeader'ampUstati 0oid Main@ string K argsBU+mlTe tCeader reader = ne) +mlTe tCeader @ "7 Xboo*s. +ml" [email protected]@BN7onsole .RriteLine@ "4irst Attrib-te 0al-e" V reader.Sal-eBN7onsole .RriteLine@ "4irst Attrib-te ;ame" Vreader.;ameBN)hile @reader.Cead@BB

    U if @reader.HasAttrib-tesB U 7onsole .RriteLine@reader.;ame V "Attrib-te" BN for @ int i = N i < reader.Attrib-te7o-ntN iVVB U reader.Mo0eToAttrib-te@iBN 7onsole .RriteLine@ ";am " V reader.;ame V ", 0al-e " Vreader.Sal-eBN W reader.Mo0eTo?lement@BN WWWW

    /ou can mo e to attri+utes +y usin( Mo0eToAttrib-te , Mo0eTo4irstAttrib-te , andMo0eTo;e tAttrib-te Mo0eTo4irstAttrib-te and Mo0eTo;e tAttrib-te mo e to thefirst and ne.t attri+utes, respecti ely #fter callin( Mo0eToAttrib-te , the ;ame,;amespa e, and Prefi property will reflect the properties of the specified attri+ute

    &ear2+ing #r a N#3e

  • 8/13/2019 Programming x Ml

    27/65

  • 8/13/2019 Programming x Ml

    28/65

    +ml'pa e Returns the current ml spa e scope

    Ta!le 6-6. xml 'ea3er Met+#3s

    8L " N&TAN"E METHO% %E&"' T ON7lose

    @lose the stream and chan(es Cead'tate to@losed9etAttrib-te Returns the alue of an attri+ute&s'tart?lement @hecks if a node has start ta(Loo*-p;amespa e Resol es a namespace prefi. in the current

    element1s scopeMo0eToAttrib-te, Mo0eTo7ontent,Mo0eTo?lement,

    Mo es to specified attri+utes, content, andelement

    Mo0eTo4irstAttrib-te,Mo0eTo;e tAttrib-te

    Mo es to the first and ne.t attri+utes

    Cead Reads a nodeCeadAttrib-teSal-e 'arses the attri+utes alue into one or more Te.t

    and=or !ntityReference node typesCead++++ @Cead7har, Cead2oolean,Cead ate, Cead&n G, and so onB

    Reads the contents of an element into thespecified type includin( char, dou+le, strin(, date,and so on

    Cead&nner+ml Reads all the content as a strin('*ip 2kips the current element

  • 8/13/2019 Programming x Ml

    29/65

    4riting XML

    The +mlRriter class contains methods and properties to write to XML documents, and+mlTe tRriter and +ml;odeRriter ome from the +mlRriter class )see fi(ure - *

    5igure 6-7. ,m

  • 8/13/2019 Programming x Ml

    30/65

    In this e.ample, you create a new XML file, c:?.ml"riterTe.t .ml, usin( XmlTe.t"riter:

    // 7reate a ne) file X mlRriterTest.+ml+mlTe tRriter )riter = ne) +mlTe tRriter @"7 XX mlRriterTest. ml" , n-ll BN

    #fter that, add comments and elements to the document usin( "rite... methods #fter that you

    can read the boo*s. ml .ml file usin( +ml Te tCeader and add its elements to mlRriterTest. ml usin( XmlTe.t"riter:

    // 7reate an +mlTe t Ceader to read boo*s. ml+mlTe tCeader reader = ne) +mlTe tCeader @ " Xboo*s. ml" BN)hile @reader.Cead@BBUif @reader.;odeType == +ml;odeType .?lementBU// Add node. ml to mlRriterTest . ml -sing Rrite;ode)riter.Rrite;ode@reader, tr-e BNWW

    Listin( -7A shows an e.ample of usin( +mlRriter to create a new document and write itsitems This pro(ram creates a new XML document, .ml writer Test, in the @:?root directory

    Listing 6-1/ ,ml

  • 8/13/2019 Programming x Ml

    31/65

    +mlTe tCeader reader = ne) +mlTe tCeader @ " Xboo*s. +ml" BN)hile @reader.Cead@BBUif @reader.;odeType == +ml;odeType .?lementBU// Add node. ml to mlRriterTest. ml -sing Rrite;ode)riter.Rrite;ode@reader, tr-e BNWW// ?nds the do -ment.)riter.Rrite?nd o -ment@BN)riter.7lose@BNret-rn NW

    NOTE: In Listin( -7A you write output of the pro(ram to a file If you want to write your outputdirectly on the console, pass 7onsole.F-t as the file name when create an +mlTe tRritero+ject &or e.ample: +mlTe tRriter )riter = ne) +mlTe tRriter @7onsole.F-t *

    "hen you open 7 X mlRriterTest.+ml in a +rowser, the output of the pro(ram looks likeListin( -7B

    Listing 6-1 . Output # ,ml - - < root >

    - < r #$ % xmlns r =" urn%record "> < &irst'ame > Mahe#h Chand < title > the Autobiography of Benjamin

    Franklin - < author >

    < &irst-name > Benjamin < last-name > Franklin

    < price > 8.99

    - < book )enre =" no el " publication*ate =" !9'* " +, ' =" (&+(!&

    '))'!&+ "> < title > The confidence man - < author >

    < first-name > Herman < last-name > Mal ille

    < price > !!.99

  • 8/13/2019 Programming x Ml

    32/65

    - < book )enre =" $hilo#ophy " publication*ate =" !99! " +, ' =" !&8'!((!&,'&' ">

    < title > The "orgia# - < author >

    < name > $lato

    < price > 9.99

    T+e 2l#se met+#3

    /ou use the 7lose method when you1re done with the +mlRriter o+ject, which closes thestream

    T+e ,ml"#n ert 2lass

    There are some characters that are not alid in XML documents XML documents use X2$ types,which are different than @RL ) N!T* data types The +ml7on0er t class contains methods tocon ert from @LR types to X2$ types and ice ersa The e ode;ame method transfers anXML name into an #$% N!T o+ject such as ataTable. The ?n ode;ame Method is there erse of e ode;ame : it con erts an #$% N!T o+ject to alid X2$ name It takes any in alidcharacter and replaces it with an escape strin( #nother method, ?n odeLo al;Ame , con ertsunpermitted names to alid names

    0esides these three methods, the +ml7on0ert class has many methods to con ert from a strin(o+ject to 0oolean 0yte, inte(er, and so on Listin( -7J shows the con ersion from 0oolean and$ate Time o+ject to XML alues

    Listing 6-14 xml 2#n ert example

    +mlTe tRriter )riter = ne) +mlTe tRriter @ " Xtest.+ml" , n-ll BN)riter.Rrite'tart?lement@ "MyTest?lements" BNbool b! = tr-e N)riter.Rrite?lement'tring@ "Test2oolean" , +ml7on0ert .To'tring@b!BBN

    ateTime dt = ne) ateTime @G , !, !BN)riter.Rrite?lement'tring@ "test date" , +ml7on0ert .To'tring@dtBBN)riter.Rrite?nd?lement@BN)riter.4l-sh@BN)riter.7lose@BN

    http://c/Documents%20and%20Settings/Administrator/Desktop/http://c/Documents%20and%20Settings/Administrator/Desktop/
  • 8/13/2019 Programming x Ml

    33/65

    9nderstanding - M Implementation

    Microsoft N!T supports the "A@ $%M Le el 7 and @ore $%M Le el D specifications The N!T&ramework pro ides $%M implementation throu(h many classes +ml;ode and +ml o -mentare two of them 0y usin( these two classes, you can easily tra erse thou(h XML documents inthe same manner you do in a tree

    T+e ,mlN#3e 2lass

    The +ml;ode class is an a+stract +ase class It represents a tree node in a document This treenode can +e the entire document This class defines enou(h methods and properties to representa document node as a tree node and tra erse thou(h it It also pro ides methods to insert,replace, and remo e document nodes

    The 7hild;odes property returns all the children nodes of current node /ou can treat an entiredocument as node and use 7hild;ode s to (et all nodes in a document /ou can use the4irst7hild, Last7hild, and Has7hild;odes triplet to tra erse from a document1s firstnode to the last node The Parent;ode, Pre0io-s'ibling, and ;e t'ibling propertiesreturn the parent and ne.t si+lin( node of the current node %ther common properties are

    #ttri+utes, 0ase RI, &nner+ml, &nner Te t, &tem ;ode Type, ;ame, Sal-e, andso on

    /ou can use the 7reate;a0igato r method of this class to create an Xpath Na i(ator o+ject,which pro ides fast na i(ation usin( .path The Append hilds, &nsertAfter, and&nsert2efore methods add nodes to the do -ment. The Cemo0e All, Cemo0e7hild, and Replace@hild methods remo e or replace document nodes, respecti ely /ou1llimplement these methods and properties in the e.ample after discussin( a few more classes

    T+e xml %#2ument "lass

    The +ml o -ment class represents an XML document 0efore it1s deri ed from the +ml;odeclass, it supports all tree tra ersal, insert, remo e, and replace functionality In spite of +ml;odefunctionaality, this class contains many useful methods

    L#a3ing a %#2ument

    $%M is a cache tree representation of an XML document The Loads and Load+ml methodsof this class load XML data and documents, and the 'a0e method sa es a document

    The Load Method can load a document from a strin(, stream, Te tCeader , or +mlCeader Thiscode e.ample loads the document boo*s. ml from a strin(:

    +ml o -ment ml o = ne) +ml o -ment @BNstring filename = " X boo*s. +ml" Nml o .Load@filenameBNml o .'a0e@ 7onsole .F-tBN

    This e ample -ses the Load method to load a do -ment from an +mlCeader

    +ml o -ment ml o = ne) +ml o -ment @BN+mlTe tCeader reader = ne) +mlTe tCeader @" XXboo*s. ml" BN

    ml o .Load@readerBN

  • 8/13/2019 Programming x Ml

    34/65

    ml o .'a0e@ 7onsole .F-tBN

    The Load+ml method loads a do -mernt from the spe ified string . 4ore ample

    ml o .Load+ml@" )rite something"BN

    &a ing a %#2ument

    The 'a0e methods sa es a document to a specified location The 2a e method takes aparamenter of Xml"riter, XmlTe.t"riter or strin( type:

    string filename = "7 X boo*s. ml" N+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@filenameBN

    +mlTe tRriter )riter = ne) +mlTe tRriter @" XXdomtest.+ml" , n-ll BN)riter.4ormatting = 4ormatting .&ndentedN

    ml o .'a0e@)riterBN

    /ou can also use a filename or @onsole %ut to sa e output as file or on the console:

    ml o .'a0e@ " XXdomtest.+ml" BNml o .'a0e@ 7onsole .F-tBN

    T+e ,ml%#2ument5ragment 2lass

    sually, you would use this class when you need to insert a small fra(ment of an XML documentor node into a document This class also comes from +ml;ode 0ecause this class is deri edfrom XmlNode, it has the same tree node tra erse, insert, remo e, and replace capa+ilities

    /ou usually create this class instance +y callin( +ml o -ment1s

    7reate o -ment4ragment method The &nner+ml represents the children of this nodeListin( -7 shows an e.ample of how to create +ml o -ment4ragme nt and load a small pieceof XML data +y settin( its &nner+ml property

    Listing 6-16. ,ml%#2ument5ragment sample

    //open an +ML filestring filename = " Xboo*s. ml" N+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@filenameBN// 7reate a do -ment fragment.+ml o -ment4ragment do 4rag = ml o .7reate o -ment4ragment@BN// 'et the ontents of the do -ment 4ragment.

    do 4rag.&nner+ml = " )rite something" N// isplay the do -ment fragment.7onsole .RriteLine@do 4rag.&nner+mlBN

    /ou can use +ml;od e methods to add, remo e, and replace data Listin( -7 appends a nodein the document fra(ment

    Listing 6-17. Appen3ing in an ,ML 3#2ument ragment

    +ml o -ment do = ne) +ml o -ment @BN

  • 8/13/2019 Programming x Ml

    35/65

    do .Load+ml@ " " V" A F.;?T programming " V "" BN// 9et the root node+ml;ode root = do . o -ment?lementN// 7reate a ne) node.+ml?lement ne)boo* = do .7reate?lement@ "pri e" BNne)boo*.&nnerTe t = " .6I" N// Add the node to the do -ment.root.Append7hild@ne)boo*BNdo .'a0e@ 7onsole .F-tBN

    T+e ,ml Element "lass

    #n +ml?lement class o+ject represents an element in a document This class comes from the+mlLin*ed;ode class, which comes from +ml;ode )see fi(ure -9*

    5igure 6-9. xml element in+eritan2e

    The +mlLin*ed;ode has two useful properties ;e t'ibing and pre0io-s'ibling #stheir names indicate, these properties return the ne.t and pre ious nodes of an XML document1scurrent node

    The +ml?lement class implements and o errides some useful methods for addin( and remo in(attri+utes and element )see ta+le - *

    Ta!le 6-7. me xml element met+#3s

    METHO% %E&"' T ON9etAttrib-te Returns the attri+ute alueHasAttrib-te @hecks if a node has the specified attri+uteCemo0eAll Remo es all the children and attri+utes of the current nodeCemo0eAllAttrib-tes, Remo es all attri+utes and specified attri+utes from an element

  • 8/13/2019 Programming x Ml

    36/65

    Cemo0eAttrib-te respecti elyCemo0eAttrib-teAt Remo es the attri+ute node with the specified inde. from the

    attri+ute collectionCemo0eAttrib-te;ode Remo es an +mlAttrib-te'etAttrib-te 2ets the alue of the specified attri+ute'etAttrib-te ;ode #dds a new .ml #ttri+ute

    In the later e.amples I1ll show you how you can use these methods in your pro(rams to (et andset XML element attri+utes

    A33ing N#3es t# a %#2ument

    /ou can use the Append7hild method to add to an e.istin( document T he Append7hildmethod ta*es a single parameter of +ml;ode type. The +ml o -ment1s7 reate... methods can create different types of nodes &or e.ample, the 7reate7omment and7reate?lement methods create comment and element node types Listin( -79 shows ane.ample of addin( two nodes to a document

    Listing 6-19. A33ing n#3es t# a 3#2ument+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load+ml@ " some 0al-e " BN// Adding a ne) omment node to the do -ment+ml;ode node! = ml o .7reate7omment@ " FM Testing sample" BN

    ml o .Append7hild@node!BN// Adding a 4irst ;ame to the do -menttnode! = ml o .7reate?lement@ "4irst ;ame" BNnode!.&nnerTe t = "Mahesh" N

    ml o . o -ment?lement.Append7hild@node!BNml o .'a0e@ 7onsole .F-tBN

    $etting t+e '##t N#3e

    The o -ment?lement method of the +ml o -ment class )inherited from +ml;ode * returnsthe root node of a document The followin( e.ample shows you how to (et the root of a document)see listin( -78*

    Listing 6-1>. $etting r##t n#3e # a 3#2ument

    string filename = " Xboo*s. ml" N+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@filenameBN+ml?lement root = ml o . o -ment?lementN

    'em# ing an3 'epla2ing N#3es

    The Cemo0eAll method of the +ml;ode class can remo e all elements and attri+utes of anode The Cemo0e7hild remo es the specified child only The followin( e.ample callsCemo0eAll to remo e all elements had attri+utes Listin( -DC calls Cemo0eAl l to remo e allitem of a node

    Listing 6-*?. 'em# ing all item # a n#3e

    p-bli stati 0oid Main@B

  • 8/13/2019 Programming x Ml

    37/65

    U// Load a do -ment fragment+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load+ml@ "" V" A F.;?T programming " BN+ml;ode root = ml o . o -ment?lementN7onsole .RriteLine@ "+ML o -ment 4ragment" BN7onsole .RriteLine@ "= = = = = = = = = = = " BN

    ml o .'a0e@ 7onsole .F-tBN7onsole .RriteLine@BN7onsole .RriteLine@ "%%%%%%%%%%%"BN7onsole .RriteLine@ "+ML o -ment 4ragment Cemo0e All" BN7onsole .RriteLine@ "= = = = = = = = = = =" BN// Cemo0e all attrib-te and hild nodes.root.Cemo0eAll@BN// isplay the ontents on the onsole after// Cemo0ing elements and attrib-tes

    ml o .'a0e@ 7onsole .F-tBNW

    NOTE: /ou can apply the Remo e #ll method on the +ooks .ml files to delete all the data, +utmake sure to ha e +ackup copy firstE

    Listin( -D7 shows how to delete all the item of +ooks Xml

    Listing 6-*1."2alling'em# eAll #r !##ks.,ml

    p-bli stati 0oid Main@BUstring filename = " XX boo*s.+ml" N+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@filenameBN+ml;ode root = ml o . o -ment?lementN7onsole .RriteLine@ "+ML o -ment 4ragment" BN7onsole .RriteLine@ "= = = = = = = = = = = " BN

    ml o .'a0e@ 7onsole .F-tBN7onsole .RriteLine@BN7onsole .RriteLine@ "% % % % % % % % % " BN7onsole .RriteLine@ "+ML o -ment 4ragment After Cemo0eAll" BN7onsole .RriteLine@ "= = = = = = = = = = = = " BN//Cemo0e all attrib-te and hild nodes.root.Cemo0eAll@BN// isplay the ontents on the onsole after// Cemo0ing elements and attrib-tes

    ml o .'a0e@ 7onsole .F-tBNW

    The Cepla e7hild method replaces an old child with a new child node In Listin( -DD,Cepla e7hild replaces root Node Last 7hild )ith ml o 4rag.

    Listing 6-** 'epla2e "+il3 met+#3 sample

    string filename = "7 Xboo*s. ml" N+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@filenameBN+ml?lement root = ml o . o -ment?lementN

  • 8/13/2019 Programming x Ml

    38/65

    +ml o -ment4ragment ml o 4ragment = ml o .7reate o -ment4ragment@BNml o 4ragment.&nner+ml =

    "" N+ml?lement root;ode = ml o . o -ment?lementN//Cepla e ml o 4ragment )ith root;ode.Last7hildroot;ode.Cepla e7hild@ ml o 4ragment, root;ode. Last7hildBN

    ml o .'a0e@ 7onsole .F-tBN

    nserting ,ML 5ragments int# an ,ML %#2ument

    #s discussed pre iously, the +ml;ode class is useful for na i(atin( throu(h the nodes of adocument It also pro ides other methods to insert XML fra(ments into a document &or instance,the &nsertAfter method inserts a document or element after the current node This methodtakes two ar(uments The first ar(ument is an +ml o -ment4ragment o+ject, and the secondar(ument is the position of where you want to insert the fra(ment #s discussed earlier in thisarticle, you create an +ml o -ment4ragment class o+ject +y usin( the7reate o -ment4ragment method of the +ml o -men t class Listin( -DA inserts an XMLfra(ment into a document after the current node usin( &nsertAfter.

    Listing 6-*/. nserting an ,ML ragment int# a 3#2ument+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@ "7 XX boo*s.+ml" BN+ml o -ment4ragment ml o 4ragment = ml o .7reate o -ment4ragment@BN

    ml o 4ragment.&nner+ml ="< 4ragment >< 'ome ata> 4ragment ata

  • 8/13/2019 Programming x Ml

    39/65

    'ransformation and X;L'

    !.tensi+le 2tylesheet Lan(ua(e )X2L* is a lan(ua(e for e.pressin( stylesheets 2tylesheetsformat XML documents in a way so that the XML data can +e presented in a certain structure in a+rowser or other media such as catalo(s +ooks and so on

    The XML stylesheet processor reads an XML document )@alled an XML source tree* andstylesheet, and it presents the document data in an XML tree format This processin( is X2LTransformation )X2LT* 2ee fi(ure -8

    5igure 6->. ,&L trans #rmati#n

    The result tree (enerated after XML transformation contains element and attri+ute nodes Theresult tree is also called an element Fattri+ute or tree In this tree, an o+ject is an XML element,and properties are attri+ute- alue pairs

    The X2L stylesheet plays a ital role in the X2LT process # stylesheet contains a set of tree

    construction rules, which ha e two parts The first part is a pattern of elements in the source tree,and the second is a template for the result tree The X2L parser reads the pattern and elementsfrom the source tree and then (enerates results accordin( to the result tree template

    ,&LT in .NET

    In the N!T &ramework, the +slTransform class impleme nts the +'LT spe ifi ation.This class you defined in a separate namespace called 'ystem.+ml.+sl Make sure you add areference to this namespace +efore usin( the +slTransfor m class /ou can use theXslt!.ception class to handle e.ceptions thrown +y an X2LT transformation

    T+e Trans #rm Met+#3

    The Transform Method of +slTransaform s data usin( loaded stylesheet and outputs theresult dependin( on the ar(ument This method has ei(ht o erloaded forms /ou can write outputof Transform in the form of +mlRriter, stream, Te tRriter, or +Path;a0igator)I1ll discuss +Path;a0igator later in this article *

    Trans #rming a %#2ument

    &ollow these steps to perform the transformation:

  • 8/13/2019 Programming x Ml

    40/65

    #. &irst you need to create an slTransform o+ject:

    +slTransform slt = ne) +slTransform @BN

    D Now, you load the stylesheet usin( the Load method:

    slt.Load@ "stylesheet4rmt. sl" BN

    A &inally, call the Transform method of XslTransform:

    slt.Transform@ " mlfile. ml" , "file.html" BN

    Example

    0efore you use +slTransform in your application, you need to add couple of namespacereferences to your application These namespace are 'ysem.+ml, 'ystem.+ml.+Path, and'ystem.+ml.+sl )I1ll discuss the + path namespace in more detail in the 5Na i(ation inHTML6 section of this article * This e.ample uses the +ooks .sl schema file that comes withthe N!T 2$U sample )see listin( -DJ*

    Listing 6-*4. ,&L Trans #rmati#n sample 2#3e

    // 7reate a ne) +slTransform ob3e t and load the stylesheet+slTransform slt = ne) +slTransform @BN

    slt.Load@ " Xboo*s.+sl" BN// 7reate a ne) +Path o -ment and load the +ML data to be transformed.+Path o -ment mydata = ne) +Path o -ment @ " X boo*s . ml" BN// 7reate an +mlTe tRriter )hi h o-tp-t to the onsole.+mlRriter )riter = ne) +mlTe tRriter @7onsole .F-tBN// Transform the data and send the o-tp-t to the onsole.

    slt.Transform@mydata, n-ll , )riterBN

  • 8/13/2019 Programming x Ml

    41/65

    Connecting -ata and XML ia +- .()'

    2o far in this article, you1 e seen how to work with XML documents In this section, you1ll nowlearn how to work with XML documents with the help of #$% N!T There are two approaches towork with XML and #$% &irst, you can use #$% N!T to access XML documents 2econd, you

    can use XML and #$% N!T to access XML #dditionally, you can access a relational data+aseusin( #$% N!T and XML N!T

    'ea3ing ,ML using a %ata&et

    In #$% N!T, you can access the data usin( the ata'et class The ata'et class implementsmethods and properties to work with XML documents The followin( sections discuss methodsthat read XML data

    T+e 'ea3,ml Met+#3

    Cead+ml is an o erloaded method you can use it to read a data stream, Te tCeader,+mlCeader, or an +M L file and to store into a ata'et o+ject, which can later +e used to

    display the data in a ta+ular format The Cead+ml method has ei(ht o erloaded forms It canread a te.t, strin(, stream, Te tCeader, +mlCeader , and their com+ination formats In thefollowin( e.ample, create a new ata'et o+ject

    In the followin( e.ample, create a new ata'et o+ject and call the ata'et. ReadXml methodto load the +ooks .ml file in a ata'et o+ject:

    //7reate a ata'et ob3e t ata'et ds = ne) ata'et@BN // 4ill )ith the data ds.Cead+ml@ "boo*s. ml " BN

    %nce you1 e a ata'et o+ject, you know how powerful it is Make sure you pro ide the correctpath of +ooks .ml

    NOTE: Make sure you add a reference to 'ystem. ata and the 'ystem. ata.7ommonnamespace +efore usin( $ata2et and other common data components

    T+e 'ea3,ml&2+ema met+#3

    The Cead+ML' hema method reads an XML schema in a ata'et o+ject It has fouro erloaded forms /ou can use a Te t Ceader , strin(, stream, and +mlCeader The followin(e.ample shows how to use a file as direct input and call the Cead+ml' hema method to read thefile:

    ata'et ds = ne) ata'et@ BNds.Cead' hema @ " Xboo*s. ml" BN

    The followin( e.ample reads the file +mlCeader and -ses +mlTe tCeader as the inputof Cead+ml' hema :

    //7reate a dataset ob3e tata'et ds = ne) ata'et@ ";e) ata'et" BN

    // Cead sl in an +mlTe tCeader

  • 8/13/2019 Programming x Ml

    42/65

  • 8/13/2019 Programming x Ml

    43/65

    ds.A ept7hanges@BN// 7reate a ne) 'treamRriter// &1ll sa0e data in std ata.+ml file'ystem.&F. 'treamRriter my'treamRriter = ne)'ystem.&F. 'treamRriter @ " Xstd ata. ml" BN// Rriter data to ata'et )hi h a t-ally reates the fileds.Rrite+ml@my'treamRriterBNmy'treamRriter.7lose@BNW

    at h @ ? eption eBU7onsole .RriteLine@ "? eption U W" , e.To'tring@BBNWret-rn N

    WWW

    /ou wouldn1t +elie e the Rrite+ml method does for you If you see the output std ata. ml

    file, it (enerates a standard XML file that looks like listin( -D

    Listing 6-*7. - < ,tu*ent >

    < 'ame > Mahe#h Chand Mike "old Mike "old

  • 8/13/2019 Programming x Ml

    44/65

    ds.Tables.Add@stdTableBN// Add st-dent ata to the table

    ataCo) ne)Co)N ne)Co) = stdTable.;e)Co)@BNne)Co)K ";ame" = "Mahesh hand" Nne)Co)K "Address" = "Meado)la*e r, to)n" NstdTable.Co)s.Add@ne)Co)BNne)Co) = stdTable.;e)Co)@BNne)Co)K ";ame" = "Mi*e 9old" Nne)Co)K "Address" = ";e)Jor*" NstdTable.Co)s.Add@ne)Co)BNds.A ept7hanges@BN+mlTe tRriter )riter = ne) +mlTe tRriter @7onsole .F-tBNds.Rrite+ml' hema@)riterBN

    Refer to the pre ious section to see how to create an +mlTe tRriter o+ject

    ,ml%ata%#2ument an3 ,ML

    #s discussed earlier in this article, the +ml o -ment class pro ides $%M tree structure of XMLdocuments The +ml ata o -ment class comes from +ml o -ment , which is comes from+ml;ode.

    &i(ure -7C shows the Xml$ata$ocument hierarchy

    5igure 6-1?. ,ml %ata %#2ument +ierar2+y

    0esides o erridin( the methods of +ml;ode and +ml o -ment, +ml ata o -ment alsoimplements its own methods The +ml ata o -men t class lets you lead relational data usin( the

    ata'et o+ject as well as XML documents usin( the Load and Load+ml methods #s fi(ure-77 indicates, you can use a ata'et to load relational data to an +ml ata o -me nt o+ject

    and use the Load or Load+ml methods to read an XML document &i(ure -77 shows arelationship +etween a Ceader, Rriter, ata'et, and +ml ata o -ment.

  • 8/13/2019 Programming x Ml

    45/65

  • 8/13/2019 Programming x Ml

    46/65

    L#a3ing %ata sing a DataSet

    # ata'et o+ject has methods to read XML doc -ments. These methods are Cead+ml' hemaand Load+ml /ou use the Load or Load+ml methods to load an XML document the sameway you did directly from the +ML ata o -ment. #(ain the Load method takes a parameter of

    a filename strin(, Te tCeader, or +mlCeader 2imilarly, use the Load+ml method to passan XML filename throu(h the dataset &or e.ample:

    +ml ata o -ment do = ne) +ml ata o -ment @ BNdo . ata'et.Cead+ml' hema @ "test. +sd" BN

    Fr

    do . ata'et .Cead+ml @ " )rite something " BN

    %isplaying ,ML %ata n a %ata&et 5#rmat

    #s mentioned pre iously, you can (et ata'et o+ject from an +ml ata o -ment o+ject +y

    usin( its ata'et property %U, now it1s time to see how to do that The ne.t sample will showyou how easy is to display an XML document data in a ata'et format

    To read XML document in a dataset, first you read to document /ou can read a document usin(the Cead+ml method of the ata'et o+ject The ata'et property of +ml ata o -mentrepresents the dataset of +ml ata o -men t #fter readin( a document in a dataset, you cancreate data iews from the dataset, or you can also use a ata'et1s efa-ltSie)Manage rproperty to +ind to data-+ound controls, as you can see in the followin( code:

    +ml ata o -ment ml atado = ne) +ml ata o -ment @BNml atado . ata'et.Cead+ml @ " XX ml ata o . ml" BN

    data9rid!. ata'o-r e = ml atado . ata'et. efa-ltSie)ManagerN

    Listin( -D8 shows the complete code #s you can see from Listin( -D8, I created a new dataset,2oo*s , fill from the boo*s. ml and +ind to a $ata3rid control usin( its ata'o-r e propertyTo make Listin( -D8 work, you need to create a "indows application and dra( a $ata3ridcontrol to the form #fter doin( that, you need to write the Listin( -D8 code on the &orm7constructor or 4orm load e ent

    Listing 6-*>. XmlDataDocumentSample.cs

    p-bli 4orm!@ BU

    // &nitiali(e 7omponent and other ode here // 7reate an +ml ata o -ment ob3e t and read an +ML +ml ata o -ment ml atado = ne) +ml ata o -ment @BN ml atado . ata'et.Cead+ml@ "7 XXboo*s. ml" BN // 7reate a ata'et ob3e t and fill )ith the dataset // of +ml ata o -ment ata'et ds = ne) ata'et @"2oo*s ata'et" BN ds = ml atado . ata'etN // Atta h dataset 0ie) to the ata 9rid ontrol data9rid!. ata'o-r e = ds. efa-ltSie)ManagerN

    W

  • 8/13/2019 Programming x Ml

    47/65

    The output of this pro(ram looks like igure 6-1* %nly a few lines code, and you1re all set NeathuhK

    5igure 6-1*. ,ml%ata%#2ument&ample.2s #utput

    &a ing %ata r#m a %ata&et t# ,ML

    /ou can sa e a ata'et data as an XML document usin( the 'a0e method of+ml ata o -ment #ctually, +ml ata o -ment comes from +ml o -ment , and the+ml o -ment class defines the 2a e method I1 e already discussed that you can use 2a emethod to sa e your data in a strin(, stream, Te tRriter, and +mlRriter.

    &irst, you create a ata'e t o+ject and fill it usin( a ataAdapte r The followin( e.ample readsthe @ustomers ta+le from the Northwind #ccess data+ase and fills data from the read to the

    ata'et

    string 'DL'tmt = "'?L?7T Y 4CFM 7-stomers" Nstring 7onne tion'tring ="Pro0ider=Mi rosoft.Oet.FL? 2. . N ata 'o-r e=7 XX ;orth)ind.mdb" N// 7reate data adapterFle b ataAdapter da = ne) Fle b ataAdapter @'DL'tmt, 7onne tion'tringBN// reate a ne) dataset ob3e t and fill -sing data adapter1s fill method

    ata'et ds = ne) ata'et @BN

    da.4ill@dsBN

    Now, you create an instance of +ml ata o -ment with the ata'et as an ar(ument and callthe 'a0e method to sa e the data as an XML document:

    +ml ata o -ment do = ne) +ml ata o -ment @dsBNdo .'a0e@ "7 XX+ml ata o . ml" BN

  • 8/13/2019 Programming x Ml

    48/65

  • 8/13/2019 Programming x Ml

    49/65

    'ra ersing XML -ocuments

    #s you1 e seen, +ml;ode pro ides a way to na i(ate $%M tree with the help of its4irst7hild, 7hild;odes, Last7hild, Pre0io-s;ode, ;e t'ibling, andPre0io-s'ibling methods

    0esides +ml;ode , the XML N!T has two more classes, which help you na i(ate XMLdocuments These classes are +Path o -ment and +Path;a0igator The'ystem.+ml.+path namespace defines +oth these classes

    The +Path namespace contains classes to pro ide read-only, fast access to documents 0eforeusin( these classes, you must add a reference of the 'ystem.+ml.+path namespace to yourapplication

    +Path;ode&terator, +Path? pression, and +Path? eption are other classesdefined in this namespace The +Path;ode&terator class pro ides iteration capa+ilities to anode . +Path? pression pro ides selection criteria to select a set of nodes from a document+ased on those criteria, and the +Path? e tion class is an e.ception class The+Path o -ment class pro ides a fast cache for XML document processin( usin( X2LT andX'ath

    /ou use the +Path o -ment constructor to create an instance of +mlPath o -ment It hasmany o erloaded constructors /ou can pass an +mlCeader, Te tCeader, or e en directXML filenames

    T+e , at+Na igat#r 2lass

    The +Path;a0igator class implements the functionality to na i(ate throu(h a document Ithas easy-to-use and self-e.planatory methods /ou create an +Path;a0igator instance +ycallin( +Ppath o -ment1s 7reate;a0igator method

    /ou can also create a +Path;a0igator o+ject +y callin( +ml o -ment1s7reate;a0igator method &or e.ample, the followin( code calls +ml o -ment Zs7reate;a0igator method to create a +Path;a0igator o+ject:

    // Load boo*s. ml do -ment+ml o -ment ml o = ne) +ml o -ment @BN+ml o .Load@ " X boo*s. ml" BN// 7reate +Path;a0igator ob3e t by alling reate ;a0igator of+ml o -ment+Path;a0igator na0 = ml o .7reate;a0igator@BN

    NOTE: $on1t for(et to add a reference of the 'ystem.+ml .+Path to your project +efore usin(any of its classes

    +Path;a0igator contain methods and properties to mo e to the first, ne.t, child, parent, androot nodes to the document

    , at+Na igat#r m# e met+#3s

    Ta+le -9 descri+es the +Path;a0igator class1s mo e methods 2ome of these methods areMo0eTo4irst, mo0eTo;e t , Mo0eToroot, Mo0eTo4irstAttrib-te,

  • 8/13/2019 Programming x Ml

    50/65

    Mo0eTo4irst7hild, Mo0eTo&d, Mo0eTo;amespa e, Mo0eToPre0io-s,Mo0eToParent and so on.

    Ta!le 6-9. , at+Na igat#r Meme!ers

    MEM8E' %E&"' T ONMo0eToAttrib-te Mo es to an attri+uteMo0eTo4irst Mo es to the first si+lin( of the current nodeMo0eTo4irstAttrib-te Mo es to the first attri+uteMo0eTo4irst7hild Mo es to the first child of the current nodeMo0eTo4irst;amespa e Mo es the X 'ath Na i(ator to the first namespace node

    of the current elementMo0eTo&d Mo es to the node with specified I$Mo0eTo;amespa e Mo es to the specified namespaceMo0eTo;e t Mo es to the ne.t node of the current nodeMo0eTo;e tAttrib-te Mo es to the ne.t #ttri+uteMo0eTo;e t;amespa e Mo es to the Ne.t namespaceMo0eToParent Mo es to the parent of the current nodeMo0eToPre0io-s Mo es to the pre ious si+lin( of the current nodeMo0eToCoot Mo es to the root node

    2o, with the help of these methods, you can mo e throu(h a document as a $%M tree Listin( -A7 uses the Mo0eToCoot and Mo0eTo4irst7hild methods to mo e to the root node andfirst child of the root node %nce you ha e a root, you can display correspondin( information suchas name, alue, node type, and so on

    Listing 6-/1. M# ing t# r##t an3 irst 2+il3 n#3es using ,pat+Na igat#r

    // Load boo*s. ml do -ment+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@ " X boo*s. ml" BN// 7reate +Path;a0igator ob3e t by alling 7reate;a0igator of

    +ml o -ment+Path;a0igator na0 = ml o .7reate;a0igator@BN//Mo0e to root nodena0.Mo0eToCoot@BNstring name = na0.;ameN7onsole .RriteLine@ "Coot node info " BN7onsole .RriteLine@ "2ase EC&" V na0.2aseEC&.To'tring@BBN7onsole .RriteLine@ ";ame " V na0.;ame.To'tring@BBN7onsole .RriteLine@ ";ode Type " V na0.;odeType.To'tring@BBN7onsole .RriteLine@ ";ode Sal-e " V na0.Sal-e.To'tring@BBNif @na0.Has7hildrenBUna0.Mo0eTo4irst7hild@BNW

    Now, usin( the Mo0eTo;e t and Mo0eToParent methods, you can mo e throu(h the entiredocument Listin( -AD Mo es thou(h an entire document and displays the data on the consoleThe 9et;ode&nfo method displays a node1s information, and you call it recursi ely

    Listing 6-/*. 'ea3ing a 3#2ument using ,pat+Na igat#r

    stati 0oid Main@ string K argsBU

  • 8/13/2019 Programming x Ml

    51/65

    // Load boo*s. ml do -ment+ml o -ment ml o = ne) +ml o -ment @BN

    ml o .Load@ " X boo*s. ml" BN// 7reate +Path;a0igator ob3e t by alling 7reate;a0igator of+ml o -ment+Path;a0igator na0 = ml o .7reate;a0igator@ BN// mo0e to root nodena0.Mo0eToCoot@BNstring name = na0.;ameN7onsole .RriteLine@ "Coot node info " BN7onsole .RriteLine@ "2ase EC&" V na0.2aseEC&.To'tring@BBN7onsole .RriteLine@ ";ame " V na0.;odeType.To'tring@BBN7onsole .RriteLine@ ";ode Type " V na0.;odeType.To'tring@BBN7onsole .RriteLine@ ";ode Sal-e " V na0.Sal-e.To'tring@BBNif @na0.Has7hildrenBUna0.Mo0eTo4irst7hild@BN9et;ode&nfo@na0BNWW

    pri0ate stati 0oid 9et;ode&nfo@ +Path;a0igator na0!BU7onsole .RriteLine@ ";ame " V na0!.;ame.To'tring@BBN7onsole .RriteLine@ ";ode Type " V na0!.;odeType.To'tring@BBN7onsole .RriteLine@ ";ode 0al-e " V na0!.Sal-e.To'tring@BBN// &f node has hildren, mo0e to first hild.if @na0!.Has7hildrenBUna0!.Mo0eTo4irst7hild@BN)hile @na0!.Mo0eTo;e t@BBU9et;ode&nfo@na0!BNna0!.Mo0eToParent@BNWWelse /Y ?lse mo0e to ne t sibling Y/Una0!.Mo0eTo;e t@BN9et;ode&nfo@na0!BNWW

    &ear2+ing using , at+Na igat#r

    'ele t, 'ele t7hildren, 'ele tAn estors, and 'ele t es endents are otheruseful methods 2pecifically, these methods are useful when you need to select a document1sitems +ased on an X'ath e.pression &or e.ample, you could use one when selectin( nodes forthe author ta( only and so on Now, say you want to search and display all ta(nodes in the boo*s. ml document

    In listin( -AA, you use +Path;a0igator1s 'ele t method to apply a criteria )all elementswith the author-name ta(* to read and display all nodes

    Listing 6-//. se of XPathIterator an3 Select

    // Load boo*s. ml do -ment

  • 8/13/2019 Programming x Ml

    52/65

    +ml o -ment ml o = ne) +ml o -ment @BNml o .Load @ " X boo*s. ml" BN

    // 7reate +Path;a0igator ob3e t by alling 7reate;a0igator of+ml o -ment+Path;a0igator na0 = ml o .7reate;a0igator@BN// Loo* for a-thor1s first name7onsole .RriteLine@ "A-thor 4irst ;ame" BN+Path;ode&terator itrator= na0.'ele t@ "des endant first%name" BN)hile @itrator.Mo0e;e t@BBU7onsole [email protected]'tring@BBNW

  • 8/13/2019 Programming x Ml

    53/65

    XML -esigner in >isual ;tudio .()'

    XML schemas play major in the N!T &ramework, and isual studio N!T pro ides many toolsand utilities to work with XML The N!T &ramework uses XML to transfer data from oneapplication to another XML schemas define the structure and alidation rules of XML document

    /ou use XML schemas definition )X2$* lan(ua(e to define XML schemas

    2 N!T pro ides an XML desi(ner to work with schemas In this section you1ll see how you cantake ad anta(e of the 2 N!TXML desi(ner and wi4ard features to work with XML $ocumentsand data+ase

    $enerating a Ne &2+ema

    To (enerate a new schema, create a new "indows application usin( &ile < New < 'roject . %ata&et-3eri e3 2lass in t+e "lass Bie

    NOTE: The 3enerate $ata 2et option may not (enerate a $ata 2et if the XML schema is notdesi(ned properly

    %nce you1 e a ata'et o+ject, you can use it the way you want

    &ummary

    This article co ered XML synta. as well the uses of XML on the N!T platform /ou learneda+out the $%M structure and $%M node types /ou learned how XML is represented in N!Tthrou(h classes such as +ml;ode, +mlAttrib-te, +ml?lement, and +ml o -ment/ou also learned how to read and write to these structures usin( the +mlCeader and+mlRriter classes #lso discussed was the na i(ation in an XML node structure usin(+mlPath;a0igator Most importantly, you learned how XML applies to #$% N!T and how touse a ata'e t to read and write data with XML isual 2tudio N!T pro ides XML $esi(ner towork with XML sin( XML $esi(ner, you can (enerate XML schema, which later can +e used to(enerate typed datasets