views:

41

answers:

2

I need t parse xml for an applescript project and i got a start but for some reason my code is not operating the way I expected it to it does find the item I'm looking for but does not return a value

here is the code

 set xmlFile to ((choose file without invisibles) as string)
 tell application "System Events"
    set xdata to XML element 1 of contents of XML file xmlFile
    set foo to my getxml(xdata, "line1")
    return foo
 end tell

 on getxml(xmldata, e)
    tell application "System Events"
        repeat with i from 1 to count of XML elements of xmldata
            set e_name to (get name of XML element i of xmldata) as Unicode text
            log e_name
            if e_name is equal to e then
                display dialog "hello"
                return value of XML element i of xmldata
            else
                my getxml(XML element i of xmldata, e)
            end if
        end repeat
    end tell
 end getxml

here is the xml

 <?xml version="1.0" encoding="UTF-8"?>
 <foo>
    <bar>
        <line1>test</line1>
    </bar>
    <crap>ohh</crap>
 </foo>

what is interesting is if i give it a top level item liKe it does what I expect it to

so I'm jsut either looking to fix this code or make something better maybe something from the shell that I can call to parse my xml ?

thanks

+2  A: 

When you recurse through the XML nodes, you're not returning the value back up through the returns from getxml().

Suggest something like replacing the line in getxml():

my getxml(XML element i of xmldata, e)

with:

set foo to my getxml(XML element i of xmldata, e)
return foo

Worked for me.

martin clayton
A: 

In shell you could try xmlstarlet http://xmlstar.sourceforge.net/ or even better use nokogiri in Ruby.

Zygmunt