By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,473 Members | 1,278 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,473 IT Pros & Developers. It's quick & easy.

Parsing hierarchical tabbed string data into XML

P: n/a
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!

Jun 11 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
craigslist...@gmail.com wrote:
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,

--
Bart

Jun 12 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.