AsObjC: Parse XML content as Record sample

Assuming all child members of the node has string value.

Note: use “Open this Scriplet in your Editor” button. Don’t copy my script (and any other script on this site) manually, to avoid additional strange problems.


use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theXML to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<BrightSignUserVariables>
   <BrightSignVar name=\"CurrentLetter\">W</BrightSignVar>
   <dict>
    <note>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
    </note>
  </dict>
   <BrightSignVar name=\"CurrentUserName\">&Q&W&Q&W&Q&W&Q&W</BrightSignVar>
</BrightSignUserVariables>"

set parentNodeName to "note"
set {childNames, childValues} to my childrenNamesAndValues:{theXML, parentNodeName}
my recordFromLabelsAndValues:{childNames, childValues}


on childrenNamesAndValues:{theXML, parentNodeName}
	set {theXMLDoc, theError} to my (NSXMLDocument's alloc()'s initWithXMLString:theXML ¬
		options:(my NSXMLDocumentTidyHTML) |error|:(reference))
	set {theMatches, theError} to ¬
		theXMLDoc's nodesForXPath:("//" & parentNodeName) |error|:(reference)
	if theMatches = missing value then error (theError's localizedDescription() as text)
	tell (theMatches's firstObject()'s children()) to ¬
		set {childNames, childValues} to {its |name|, its stringValue}
end childrenNamesAndValues:


on recordFromLabelsAndValues:{theseLabels, theseValues}
	set theResult to my (NSDictionary's dictionaryWithObjects:theseValues forKeys:theseLabels)
	return theResult as record
end recordFromLabelsAndValues: