use scripting additions
use framework "Foundation"
on extractFrom:thePath matchingXPath:theQuery
set anNSURL to current application's |NSURL|'s fileURLWithPath:thePath -- make NSURL
set {theNSXMLDocument, theNSError} to current application's NSXMLDocument's alloc()'s initWithContentsOfURL:anNSURL options:0 |error|:(reference) -- make XMLDoc
if theNSXMLDocument = missing value then -- there's a problem
display dialog (theNSError's localizedDescription()) as text
error number -128
end if
set attStrings to {} -- where attributes will be stored
set theXMLOutput to current application's NSXMLElement's alloc()'s initWithName:"output" -- found nodes added to this
set {theResults, theNSError} to (theNSXMLDocument's nodesForXPath:theQuery |error|:(reference)) -- query
if theResults is not missing value then
repeat with anNSXMLNode in (theResults as list)
anNSXMLNode's detach() -- need to detach first
if anNSXMLNode's |kind|() as integer = current application's NSXMLAttributeKind then -- see if it's an attribute or node
set end of attStrings to (anNSXMLNode's stringValue()) as text
else
(theXMLOutput's addChild:anNSXMLNode) -- add node
end if
end repeat
return {(theXMLOutput's XMLStringWithOptions:(current application's NSXMLNodePrettyPrint)) as text, attStrings} -- change options to suit
else
return missing value
end if
end extractFrom:matchingXPath:
(* This is an example of performing an XPath query, in this case retrieving the name of every item in your iTunes library. It returns an XML element called output, containing the matching nodes, plus a list of found attributes if that's what your XPath query requests *)
set thePath to POSIX path of (path to music folder) & "iTunes/iTunes Library.xml"
its extractFrom:thePath matchingXPath:"//key[text()='Name']/following-sibling::string[1]"