Parsing hierarchical tabbed string data into XML

C

craigslist.jg

Basically, I want to do this in Javascript:

I want to convert a string such as:


Cities
New York
Address 1
Address 2
Address 3
Household
John
Lucy

Los Angeles
Address 1
Address 2
Address 3
Household
Mike
Ryan



....and automatically convert this string to XML so I can traverse
through it with any XML methods that may exist.

Is there a quick and easy way to do this?

Thanks!
 
B

Bart Van der Donck

I want to convert a string such as:

Cities
New York
Address 1
Address 2
Address 3
Household
John
Lucy

Los Angeles
Address 1
Address 2
Address 3
Household
Mike
Ryan

...and automatically convert this string to XML so I can
traverse through it with any XML methods that may exist.

// data init
var D = "Cities\n"
D+="\tNew York\n"
D+="\t\tAddress 1\n"
D+="\t\tAddress 2\n"
D+="\t\tAddress 3\n"
D+="\t\t\tHousehold\n"
D+="\t\t\t\tJohn\n"
D+="\t\t\t\tLucy\n"
D+="\tLos Angeles\n"
D+="\t\tAddress 1\n"
D+="\t\tAddress 2\n"
D+="\t\tAddress 3\n"
D+="\t\t\tHousehold\n"
D+="\t\t\t\tMike\n"
D+="\t\t\t\tRyan\n"

// valid xml knows 5 character entities only
D=D.replace(/</g, '&lt;')
D=D.replace(/>/g, '&gt;')
D=D.replace(/"/g, '&quot;')
D=D.replace(/'/g, '&apos;')
D=D.replace(/&/g, '&amp;')

// regexes based on tabs
D=D.replace(/(\t{4})(.{0,})\n/g,' <name>$2</name>\n')
D=D.replace(/(\t{3})(.{0,})\n/g,' <household>$2</household>\n')
D=D.replace(/(\t{2})(.{0,})\n/g,' <address>$2</address>\n')
D=D.replace(/(\t)(.{0,})\n/g, ' <city>$2</city>\n')

// add root tag and xml header line
var lines = D.split('\n')
var root = lines[0]
delete lines[0]
D='<'+root+'>' + lines.join('\n') + '</'+root+'>'
D='<?xml version="1.0" encoding="UTF-8"?>\n' + D

// report to screen
document.write('<textarea rows="20" cols="70">'+D+'</textarea>')

Hope this helps,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top