2011-09-02 9 views

Respuesta

4

Esto es lo que he hecho:

set file_tgt to (POSIX path of (path to temporary items)) & "file.xml" 
    do shell script "curl -L " & "http://url.com/file.xml" & " -o " & file_tgt 
tell application "System Events" 
    set file_content to contents of XML file file_tgt 
    tell file_content 
     set my_value to value of XML element 1 
    end tell 
end tell 

al principio yo estaba usando la aplicación "URL de acceso de secuencias de comandos" para buscar el archivo, pero ya que se ha eliminado en León, me pasa a rizo puro, que funciona bajo Snow Leopard y Lion.

2

Encontré this thread que tiene un ejemplo de analizar un archivo XML con las herramientas XML disponibles a través de System Events. Aunque me parece bastante intrincado.

También existe este (freeware) scripting addition package para analizar/escribir XML. No lo he mirado, pero podría ser ordenado.

Personalmente, me gustaría guardar mi secuencia de comandos como un paquete de secuencia de comandos, y luego haría un pequeño script php/Ruby/perl/python/lo que sea para analizar XML (ya que estoy más cómodo con eso) en el haz. Luego usaría AppleScript y luego pasaría el XML al script del analizador desde cURL.

AppleScript:

set scriptPath to POSIX path of (path to me as alias) & "Contents/Resources/parse_xml.rb" 
set fooValue to do shell script "curl http://foo/test.xml 2> /dev/null | ruby " & quoted form of scriptPath 

parse_xml.rb podría ser algo como este (usando Rubí como ejemplo):

require "rexml/document" 

# load and parse the xml from stdin 
xml = STDIN.read 
doc = REXML::Document.new(xml) 

# output the text of the root element (<foo>) stripped of leading/trailing whitespace 
puts doc.root.text.strip 

(Ruby y el paquete REXML debe estar fácilmente disponible en cualquier Mac, por lo que debería funcionar en cualquier lugar ... creo)

El punto es que, cuando se ejecuta el script, descargará el archivo XML con cURL, lo pasará al script de Ruby y, al final, fooValue en el AppleScript se establecerá en "barra".

Por supuesto, si el XML es más complejo, necesitará más scripts, o eche otro vistazo a las otras opciones.

Probablemente haya incluso más formas de hacerlo (por ejemplo, podrías hacer algo de manipulación de cadenas en lugar de un análisis completo de XML, pero eso es un poco frágil, por supuesto), pero voy a parar aquí :)

0

Al darse cuenta de esto es una vieja pregunta, pero aquí está una manera de usar la API de Bing Maps (nota que reemplacé mi clave de API con XXXXXXXXXX). use do shell script con curl para recuperar el XML, luego recorra los elementos hasta llegar al que necesita (puede consolidar todos los tell en tell xml element “X” of xml element “y” of xml element…, pero esto es más fácil de seguir).

set theXML to make new XML data with properties {name:"Geolocation", text:(do shell script "curl 'http://dev.virtualearth.net/REST/v1/Locations?&q=638%20Brandon%20Town%20Center%20Brandon%20FL%2033511&o=xml&key=XXXXXXXXXX'")} 
tell theXML 
    tell XML element "Response" 
     tell XML element "ResourceSets" 
      tell XML element "ResourceSet" 
       tell XML element "Resources" 
        tell XML element "Location" 
         tell XML element "Point" 
          set theLatitude to the value of XML element "Latitude" 
          set theLongitude to the value of XML element "Longitude" 
         end tell 
        end tell 
       end tell 
      end tell 
     end tell 
    end tell 
end tell 

EDIT: supongo que debería incluir el código XML que estaba usando para lo anterior:

<?xml version=\"1.0\" encoding=\"utf-8\"?> 
<Response xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/search/local/ws/rest/v1\"> 
    <Copyright>Copyright © 2014 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright> 
    <BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri> 
    <StatusCode>200</StatusCode> 
    <StatusDescription>OK</StatusDescription> 
    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode> 
    <TraceId>06bb657f1ac9466ba00ef45aa55aef3b|BN20130631|02.00.108.1000|BN2SCH020180822, BN2SCH020181444, BN2SCH020181020, BN2SCH030291220, BN2SCH030261523</TraceId> 
    <ResourceSets> 
    <ResourceSet> 
     <EstimatedTotal>1</EstimatedTotal> 
     <Resources> 
     <Location> 
      <Name>638 Brandon Town Center Dr, Brandon, FL 33511</Name> 
      <Point> 
      <Latitude>27.929752349853516</Latitude> 
      <Longitude>-82.326362609863281</Longitude> 
      </Point> 
      <BoundingBox> 
      <SouthLatitude>27.925889632282839</SouthLatitude> 
      <WestLongitude>-82.332191670122214</WestLongitude> 
      <NorthLatitude>27.933615067424192</NorthLatitude> 
      <EastLongitude>-82.320533549604349</EastLongitude> 
      </BoundingBox> 
      <EntityType>Address</EntityType> 
      <Address> 
      <AddressLine>638 Brandon Town Center Dr</AddressLine> 
      <AdminDistrict>FL</AdminDistrict> 
      <AdminDistrict2>Hillsborough Co.</AdminDistrict2> 
      <CountryRegion>United States</CountryRegion> 
      <FormattedAddress>638 Brandon Town Center Dr, Brandon, FL 33511</FormattedAddress> 
      <Locality>Brandon</Locality> 
      <PostalCode>33511</PostalCode> 
      </Address> 
      <Confidence>High</Confidence> 
      <MatchCode>Good</MatchCode> 
      <GeocodePoint> 
      <Latitude>27.929752349853516</Latitude> 
      <Longitude>-82.326362609863281</Longitude> 
      <CalculationMethod>Parcel</CalculationMethod> 
      <UsageType>Display</UsageType> 
      </GeocodePoint> 
      <GeocodePoint> 
      <Latitude>27.929159164428711</Latitude> 
      <Longitude>-82.32720947265625</Longitude> 
      <CalculationMethod>Interpolation</CalculationMethod> 
      <UsageType>Route</UsageType> 
      </GeocodePoint> 
     </Location> 
     </Resources> 
    </ResourceSet> 
    </ResourceSets> 
</Response> 
Cuestiones relacionadas