Use AppleScript To Parse XML Via A URL

倾然丶 夕夏残阳落幕 提交于 2020-04-30 06:26:35

问题


I am trying to parse data from a networked media player.

I can access the data on the player via the following endpoint:

http://192.168.10.2:8008/GetUserVars

This returns the following data:-

<?xml version="1.0" encoding="UTF-8"?>
<BrightSignUserVariables>
  <BrightSignVar name="CurrentLetter">W</BrightSignVar>
  <BrightSignVar name="CurrentUserName">&amp;Q&amp;W&amp;Q&amp;W&amp;Q&amp;W&amp;Q&amp;W</BrightSignVar>
</BrightSignUserVariables>

From this I need to use AppleScript to get the values from the BrightSignVar XML element node whose name attribute is CurrentLetter and CurrentUserName.

Essentially, I want to obtain these two text nodes:

  • W
  • &amp;Q&amp;W&amp;Q&amp;W&amp;Q&amp;W&amp;Q&amp;W

I tried the following example but got errors, any ideas?

set theXMLFile to ((http://192.168.10.2:8008/GetUserVars) as string)

tell application "System Events"

    set CurrUser to (value of XML element "CurrentUserName")

    set CurrLetter to (value of XML element "CurrentLetter")

end tell

Edit:

I have also tried the following:

set theXMLFile to (do shell script (("curl -X GET 'http://192.168.10.5:8008/GetUserVars'")))

tell application "System Events"

    set CurrUser to XML elements of XML element "BrightSignVar" of XML element "BrightSignUserVariables" of theXMLFile whose name is "CurrentUserName"

end tell

This returns the response as above however I get an error when trying to set CurrUser as variable:

can't make "BrightSignUserVariables" into type integer (-1700)


回答1:


You were very close. Here's your last script with a few appropriate amendments that I believe should work:

set userVars to do shell script "curl -X GET 'http://192.168.10.5:8008/GetUserVars'"

tell application id "com.apple.SystemEvents"
    tell (make new XML data with data userVars)
        tell XML element "BrightSignUserVariables"
            tell every XML element whose name="BrightSignVar" to ¬
                set {letter, username} to its value
        end tell
    end tell
end tell

When I ran it using the XML response text you provided, the return value was:

{"W", "&Q&W&Q&W&Q&W&Q&W"}


来源:https://stackoverflow.com/questions/60511381/use-applescript-to-parse-xml-via-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!