Documentation Archive

Developer

Mac Automation Scripting Guide

Working with XML

The XML Suite of the System Events scripting dictionary defines several classes that make it quick and easy to read and parse XML data. The XML file class represents any text file containing structured XML like the example data shown in Listing 36-1.

Listing 36-1XML: Example XML data
  1. <books>
  2. <book country="US">
  3. <name>The Secret Lives of Cats</name>
  4. <publisher>Feline Press</publisher>
  5. </book>
  6. </books>

At the top level, an XML file contains an XML data object that’s comprised of nested XML element objects. Each XML element object has a name and a value property, and may also contain XML attribute objects that define additional metadata. The example code in Listing 36-2 demonstrates how to access these classes to read and parse the contents of an XML file on the Desktop that contains the XML data from Listing 36-1.

APPLESCRIPT

Open in Script Editor

Listing 36-2AppleScript: Using System Events to parse an XML file
  1. tell application "System Events"
  2. tell XML file "~/Desktop/Book Data.xml"
  3. tell XML element "books"
  4. set theBookElements to every XML element whose name = "book"
  5. --> {XML element 1 of XML element 1 of contents of XML file "Macintosh HD:Users:YourUserName:Desktop:Book Data.xml" of application "System Events"}
  6. repeat with a from 1 to length of theBookElements
  7. set theCurrentBookElement to item a of theBookElements
  8. --> XML element 1 of XML element 1 of contents of XML file "Macintosh HD:Users:YourUserName:Desktop:Book Data.xml" of application "System Events"
  9. tell theCurrentBookElement
  10. name of theCurrentBookElement
  11. --> "book"
  12. name of every XML element
  13. --> {"name", "publisher"}
  14. name of every XML attribute
  15. --> {"country"}
  16. value of every XML attribute
  17. --> {"US"}
  18. set theBookName to value of XML element "name"
  19. --> "The Secret Lives of Cats"
  20. set thePublisher to value of XML element "publisher"
  21. --> "Feline Press"
  22. end tell
  23. end repeat
  24. end tell
  25. end tell
  26. end tell