AppleScript名:recordをXMLに v2 |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set theRecord to {firstName:"Saga", lastName:"Norén", city:"Malmö"} makeXMLDocWithRecord(theRecord) –> (* "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<character>\n <firstName>Saga</firstName>\n <city>Malmö</city>\n <lastName>Norén</lastName>\n</character>" *) set theRecord to {firstName:"Saga", lastName:"Norén", city:"Malmö", partner:{firstName:"Martin", lastName:"Rohde", city:"København"}} makeXMLDocWithRecord(theRecord) –> (* "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<character>\n <firstName>Saga</firstName>\n <lastName>Norén</lastName>\n <city>Malmö</city>\n <partner>\n <firstName>Martin</firstName>\n <city>København</city>\n <lastName>Rohde</lastName>\n </partner>\n</character>" *) –Record –> XML (text) on makeXMLDocWithRecord(theRecord) — make root element set rootElement to current application’s NSXMLNode’s elementWithName:"character" — make XML document set theXMLDocument to current application’s NSXMLDocument’s alloc()’s initWithRootElement:rootElement theXMLDocument’s setDocumentContentKind:(current application’s NSXMLDocumentXMLKind) theXMLDocument’s setStandalone:true theXMLDocument’s setCharacterEncoding:"UTF-8" — make dictionary from record set anNSDictionary to current application’s NSDictionary’s dictionaryWithDictionary:theRecord — add children to root element its addChildTo:rootElement withDictionary:anNSDictionary — return as string with whatever formatting options you want return (theXMLDocument’s XMLStringWithOptions:(current application’s NSXMLNodePrettyPrint)) as text end makeXMLDocWithRecord on addChildTo:parentElement withDictionary:theDict set theKeys to theDict’s allKeys() as list repeat with i from 1 to count of theKeys set theKey to item i of theKeys set theValue to (theDict’s objectForKey:theKey) set newElement to (current application’s NSXMLNode’s elementWithName:theKey) (parentElement’s addChild:newElement) if (theValue’s isKindOfClass:(current application’s NSDictionary)) as boolean then (its addChildTo:newElement withDictionary:theValue) else (newElement’s setObjectValue:theValue) end if end repeat end addChildTo:withDictionary: |
More from my site
(Visited 26 times, 1 visits today)