Skip to content

Instantly share code, notes, and snippets.

@RobTrew
Last active December 8, 2022 23:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RobTrew/885ae95bedf369c613f2 to your computer and use it in GitHub Desktop.
Save RobTrew/885ae95bedf369c613f2 to your computer and use it in GitHub Desktop.
PARSE LOCAL OPML FILE IN OS X 10.10 JXA USING $.NSXMLDocument (parsing 'text' + all other attributes)
// PARSE LOCAL OPML FILE IN OS X 10.10 JXA USING $.NSXMLDocument
// Ver 2.0 Parse all attributes (ver 1 just parsed text)
function run() {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
function readTextFromFile(strPath) {
return $.NSString.stringWithContentsOfFile(strPath);
}
var strPath = (
app.chooseFile({withPrompt: "Choose OPML file:"})
).toString(), // Path --> String
strXML = strPath ? readTextFromFile(strPath) : '';
if (!strXML) return;
// JSExport convention:
// The letter following each ":" is capitalized, and then the ":"s are removed:
// initWithXMLString:options:error: --> initWithXMLStringOptionsError
var oXMLDoc1 = $.NSXMLDocument.alloc.initWithXMLStringOptionsError(strXML, 0, null),
// Outline nodes are children of Body - the second child of the Root
lstOutline = ObjC.unwrap(oXMLDoc1.rootElement.childAtIndex(1).children),
lstParse, strJSON;
function parseOPML(lst) {
var lstParse = [],
lstAttribs = [],
lstChiln = [],
lng = lst.length,
oNode, dctNode, i, j;
for (i = 0; i < lng; i++) {
oNode = lst[i];
dctNode = {};
// Now transfer all keyvalue pairs in outline attributes
// (Rewriting '_note' if found, as 'note')
lstAttribs = ObjC.unwrap(oNode.attributes);
j = lstAttribs.length;
while (j--) {
oAttrib = lstAttribs[j];
strKey = ObjC.unwrap(oAttrib.name);
strValue = ObjC.unwrap(oAttrib.stringValue);
if (strKey === '_note')
dctNode.note = strValue;
else dctNode[strKey] = strValue;
}
lstChiln = ObjC.unwrap(oNode.children);
if (lstChiln)
dctNode.chiln = parseOPML(lstChiln);
lstParse.push(dctNode);
}
return lstParse;
}
lstParse = parseOPML(lstOutline);
strJSON = JSON.stringify(lstParse,null, 2);
app.setTheClipboardTo(strJSON);
return lstParse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment