使用Applescript获取xml属性的值

时间:2010-04-07 04:53:41

标签: xml parsing applescript

我想解析Yahoo! Weather API和我想将这些元素属性保存到变量中供以后使用:

<yweather:location city="Zebulon" region="NC"   country="US"/>
<yweather:astronomy sunrise="6:52 am"   sunset="7:39 pm"/>
<yweather:forecast day="Wed" date="7 Apr 2010" low="61" high="96" text="Partly Cloudy" code="29" />

我怎么能用applescript做到这一点?

所以,

set locationCity to [city]
set locationRegion to [reagion]
set locationCountry to [country]

set astronomySunrise to [sunriseTime]
set astronomySunset to [sunsetTime]

我希望forcast在某种数组中按日/日组织它们

1 个答案:

答案 0 :(得分:2)

系统事件有一小组本机命令可以帮助你(未经测试):

(*
Assuming the following dummy XML:

<?xml version="1.0" encoding="UTF-8"?>
<RootTag>
    <yweather:location city="Zebulon" region="NC"   country="US"/>
    <yweather:astronomy sunrise="6:52 am"   sunset="7:39 pm"/>
    <yweather:forecast day="Wed" date="7 Apr 2010" low="61" high="96" text="Partly Cloudy" code="29" />
</RootTag>

*)

    set theXMLFile to ((choose file) as string)

    tell application "System Events"
        set theXMLData to contents of XML file theXMLFile
        tell theXMLData
            set theXMLRoot to XML element 1
        set locationTag to XML element 1 of theXMLRoot
        set cityAttribute to XML attribute 1 of locationTag
        return cityAttribute --> "Zebulon"
        end tell
    end tell

从我收集的内容来看,Applescript的XML钩子对于它的XML非常挑剔,除了“一些不是预期类型的​​数据”之外,它没有提供太多的故障排除。

我去其他地方进行XML解析,我在这里推荐相同的内容。如果需要纯粹的Applescript解决方案,我只知道XML Tools addition from Late Night Software(免费)和Satimage has a more complex set bundled with their suite(付费),但我也没有任何经验。