Tải bản đầy đủ - 0 (trang)
Hack 87. Provide Complete XML Control to Any Version of Access

Hack 87. Provide Complete XML Control to Any Version of Access

Tải bản đầy đủ - 0trang

Ifyoudon'tfindtheMicrosoftXMLreferenceonyourcomputer,

downloadtheMSXMLparserfromMicrosoft

(http://www.microsoft.com/xml).



Withthereferenceset,youcanworkwithXMLinmany

sophisticatedways.Thishackisn'ttheplacetolearnhowtouse

theparser(seetheendofthehackforsomeresources).

Instead,we'llpreviewusingtheparsertoloadXMLdataand

insertitintoanAccesstable.Alongtheway,we'llaccomplisha

coupleoftricks:filteringXMLdataandloadingattributes.

AnXMLfilefilledwithemployeeinformationhasbeenprepared,



asshowninFigure8-29.



8.17.2.TheCode

InanAccesscodemodule,thefollowingcodehasbeenentered.

Thiscodeusesobjectsavailablefromtheparserreference:



Subread_xml()

OnErrorGoToerr_end

DimconnAsNewADODB.Connection



Setconn=CurrentProject.Connection



DimxmlobjAsDOMDocument



Dimxml_listAsIXMLDOMNodeList



Dimxml_nodeAsIXMLDOMNode



Setxmlobj=NewDOMDocument



xmlobj.async=False



xmlobj.Load"C:\Employees.xml"

Setxml_list=xmlobj.selectNodes_

("Employees/Department/Employee")

ForEachxml_nodeInxml_list

ssql="InsertIntotblEmployeesValues("&_

xml_node.childNodes(0).Text&",'"&_





xml_node.childNodes(1).Text&"','"&_





xml_node.parentNode.Attributes(0).Text&"')"

conn.Executessql



Next



MsgBox"done"

err_end:

MsgBoxErr.Description

EndSub



Figure8-29.TheEmployees.xmlfile



TheXMLfileisloadedintothexmlobjobjectvariable:

xmlobj.Load"C:\Employees.xml"



TypicalXMLobjectsarenodesandnodelists.Alistisa

collectionofnodes.Theactualnodesaretheemployee

elements,whicharechildrenofthedepartmentnodes:

Setxml_list=xmlobj.selectNodes_

("Employees/Department/Employee")



Employeenodeshavetwochildren:EmployeeIDandName.These

childelementsandtheparentdepartmentelementarethe

basisfromwhichaSQLInsertstatementiscreated.



ssql="InsertIntotblEmployeesValues("&_

xml_node.childNodes(0).Text&",'"&_







xml_node.childNodes(1).Text&"','"&







xml_node.parentNode.Attributes(0).Text



Aftertheroutineruns,thetblEmployeestableispopulatedwith

theXMLdata,asshowninFigure8-30.



Figure8-30.TheXMLdatanowinAccess



So,injustashortroutine,we'veaccomplishedtwothingsthat

aretypicallytakenforgrantedasbeingimpossible.Oneisthat

now,onlyAccess2003canworkwithXMLinarobustway,and

theotheristhatattributescan'tbeimported.Theroutineinthis

hackwillworkwithanyversionofAccessthatreferencesthe

parserandclearlyhasnoproblemputtinganattribute'svalue

intoanAccesstable.



8.17.3.SeeAlso

"UseAccessasanXMLDatabase"[Hack#95]



XMLHacks(O'Reilly)

Office2003XML(O'Reilly)



Hack88.UseCustomEnumerations



Usefamiliarnames,insteadofmemorizingequivalent

numbers,toavoiderrorsandspeedupcoding.

Havingalistofpropertiesandmethodsappearwhiletyping

reallyhelpswhenyou'recoding.Forexample,entering

Applicationinacodemoduleandthenenteringaperiodopens

upalistofmethodsandpropertiesthatbelongtotheApplication

object.

Youcanusethissamehelpfulfacilitytoprovideyouwith

constantsthatareparticulartoyourprojectorbusiness.Take,

forexample,anapplicationthathastotakethedepartment

codeintoaccountforsomespecificprocessing.Each

departmenthasauniquecodenumber,butthenumbers

themselvesaremeaningless.Thismakesthecodenumbers

difficulttoremember.

Thatiswhereasetofenumeratedvariablescomesinhandy.

Notonlycanyougivenamestothenumericalcodenumbers,

butthenamesbecomeavailableinalistwhiletyping.

Figure8-31showsaVBAcodemodule.Inthedeclaration

section,IusedtheEnumstatementtocreatethevariables.Igave

anametotheblock(DepartmentCodesinthisexample)andused

theEndEnumstatementtoendtheblock.



Figure8-31.UsingEnumformoreefficientcoding



WithintheEnumblock,Iassignedeachdepartment'scode

numbertoitsname.Now,whencodingwithinaprocedure,allI

havetodoistypeDepartmentNameandenteraperiod.The

enumeratedvariablesappear,andIcanselecttheoneIneed.

Byselectingone,I'mreallyselectingthedepartmentcode

number,butInolongerhavetomemorizethenumbers.This

reduceserrorsbecausehonestly,upuntilIusedthistechniqueI

couldnotrememberifAdvertisingwas200or600.Thankfully,by

usingEnum,I'mabletoletgoofrememberingsuchthingsand

canconcentrateonthemoreimportantaspectsofmyprojects.



Hack89.ConvertTexttotheDesiredCase



Haveanytextstringbereturnedinuppercase,

lowercase,orpropercase.

Oneoftheoccasionalrequirementsthrownatadeveloperisthe

abilitytochangethecaseofthetext.Thisisn'tareallydifficult

problem.AllyouhavetodoisusetheUCaseorLCasefunctions,

whichreturnatextstringasallcapitallettersoralllowercase

letters,respectively.

However,nofunctionisavailableforreturningpropercase

(a.k.a.mixedcaseorsentencecase):textinwhicheachword

startswithanuppercaseletter,withtherestofthewordin

lowercase.

MicrosoftWordhastheabilitytoreturnpropercase,butAccess

doesn't.Whileyou'rewaitingforthetwodevelopmentteamsat

Microsofttogettogetheronthis,hereisafunctionthatreturns

allthreecasetypes:upper,lower,andproper.Thefunction

takestwoarguments:thetexttobeconvertedandthetypeof

treatmenttoapply.



8.19.1.TheCode

Whenconvertingtoupper-orlowercase,thefunctionsimply

usestherespectivebuilt-inUCaseorLCasefunction.Whyreinvent

thewheel?

Toconverttexttopropercaserequiresaloopingprocess.Ifyou

thinkaboutit,allyouneedtodoisapplyUCaseorLCasetoeach

characterinthetext.Thetrickistoknowwhichlettersget



whichtreatment.



Functionchange_case(txtAsString,case_typeAsString)AsStr

SelectCasecase_type

Case"Upper"

change_case=UCase(txt)

Case"Lower"

change_case=LCase(txt)

Case"Proper"

'createpropercase

Dimspace_flagAsBoolean



space_flag=False



'firstletterisalwayuppercase



change_case=UCase(Left(txt,1))



Fortest_case=2ToLen(txt)

IfMid(txt,test_case,1)=""Then

space_flag=True

change_case=change_case&LCase(Mid(txt,test_case,1

Else

Ifspace_flag=TrueThen

change_case=change_case&UCase(Mid(txt,test_case,



space_flag=False

Else

change_case=change_case&LCase(Mid(txt,test_case,

EndIf

EndIf

Nexttest_case

EndSelect

EndFunction



Tostart,thefirstletterofthestringbecomesuppercase.That

oneisagiven.Then,aloopcyclesthroughtherestofthetext

string.Acharactercanbeaspace.Whenaspaceis

encountered,aflagissettotrue.Whenanonspacecharacteris

encountered,oneoftwothingscanhappen:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 87. Provide Complete XML Control to Any Version of Access

Tải bản đầy đủ ngay(0 tr)

×