Wiki Home

YMLParser


Namespace: WIN_COM_API
Sometimes it's useful to have a text file for configuration settings. Here is a YAML Parser for VFP that converts a yml file into a Foxpro object. YMMV.

PARAMETERS lcYmlFile
LOCAL lcYml, loCollector
IF PCOUNT() = 0
  lcYmlFile = "configtest.yml"
ENDIF
lcYml = FILETOSTR(lcYmlFile)
loYml = NEWOBJECT("Empty")
DIMENSION gaYml[1]
ALINES(gaYml,lcYml,0)
DO parseYmlContent WITH loYml,1,0
RETURN loYml

PROCEDURE parseYmlContent
  PARAMETERS poParent,pnLine,pnIndent
  LOCAL lnIndent,lcLine, lnLine, lcTag, loTag
  FOR lnLine = pnLine TO ALEN(gaYml)
    lcLine = RTRIM(gaYml[lnLine])
    lnIndent = LEN(lcLine) - LEN(LTRIM(lcLine))
    lcLine = LTRIM(lcLine)
    DO CASE
    CASE EMPTY(lcLine)
      LOOP
    CASE LEFT(lcLine,1) $ "*;#"
      LOOP
    CASE lnIndent = pnIndent AND ":" = RIGHT(lcLine,1)
      lcTag = CHRTRAN(ALLTRIM(lcLine),":","")
      loTag = NEWOBJECT("Empty")
      ADDPROPERTY(poParent,lcTag, loTag)
    CASE lnIndent = pnIndent AND ":" $ lcLine
      lcKey = GETWORDNUM(lcLine,1,":")
      lcValue = ALLTRIM(SUBSTR(lcLine,AT(":",lcLine)+1))
      ADDPROPERTY(poParent,lcKey,lcValue)
    CASE lnIndent = pnIndent
      *-- invalid element, ignore it
    CASE lnIndent > pnIndent
      DO parseYmlContent WITH loTag,lnLine,lnIndent
    CASE lnIndent < pnIndent
      EXIT
    ENDCASE
  NEXT
  pnLine = lnLine - 1
ENDPROC


Here is a sample yml file:
# this is a test line
TEST:
   * another comment
   DOMAIN: localhost
   DB: Test
   CONN: mysql.odbc.junk

LIVE:
   DOMAIN: foxtrails
   DB: production
   CONNECTION:
      DRIVER: oracle
      USER: someuser
      PWD: hello


Contributors: Brian Marquis
( Topic last updated: 2009.02.27 10:46:19 AM )