Hi there,
I wrote a script recently that parsed certain HTML files. The project is now over, but I encountered a problem during it that I couldn’t find the solution for and was hoping somebody here had the answer.
Put simply, I wanted to change a list into a record using an iterative method, but I couldn’t figure out how. Here’s an example:
When I encountered an img tag, I would get its tag attributes out first as a string, and then convert it to a list and would wind up with something like
set thelist to {"src=imgsrc.jpg", "width=400", "height=600"}
What I would want to happen next is cycle through the list and come up with a record like
set therecord to {src:"imgsrc.jpg", width:"400", height:"600"}
I’m aware of the various XML tools that AppleScript has available to it, and was able to use them by making faux XML documents out of various bits and pieces of the original code. However, this wasn’t always what I wanted since then I’d have to figure out where in the depth of the XML file the particular tag I wanted was, and I’d have to often rewrite the HTML as I went to come up with valid XML.
What I tried and what failed was:
- Trying to assign the attributes to variables and then adding those pairs to my original record
set therecord to {} as record
set thelist to {"src=imgsrc.jpg", "width=400", "height=600"}
repeat with i from 1 to count of thelist
set AppleScript's text item delimiters to "="
set theItem to item i of thelist
set attPair to text items of theItem
set keyname to item 1 of attPair
set keyval to item 2 of attPair
set newAdd to {keyname:keyval}
set therecord to therecord & newAdd
end repeat
set AppleScript's text item delimiters to ""
which returned:
{keyname:"imgsrc.jpg"}
- Trying to coerce the string into a record with
set therecord to {} as record
set thelist to {"src=imgsrc.jpg", "width=400", "height=600"}
repeat with i from 1 to count of thelist
set AppleScript's text item delimiters to "="
set theItem to item i of thelist
set attPair to text items of theItem
set AppleScript's text item delimiters to ":"
set newAdd to (attPair as string) as record
set therecord to therecord & newAdd
end repeat
set AppleScript's text item delimiters to ""
which returned:
{«class ktxt»:"src:imgsrc.jpg"}
Is what I’m proposing possible? Every example I’ve encountered when making records always has the record creation written explicitly into the code, like what I wrote at the top of this post.
I’m on OS 10.6, AppleScript 2.0.1
Thank you for your time.
Carl