Last active
December 30, 2021 23:44
-
-
Save Varriount/0069395761069e3bc7adb1569dab3f55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// let realRawData = `...` | |
// Note: The following code uses inconsistant processing strategies for the purposes of example. | |
{ | |
//// Utility Functions //// | |
const querySelectorAll = (node, expr) => node.querySelectorAll(expr); | |
const querySelector = (node, expr) => node.querySelector(expr); | |
function* queryXPathAll(node, expr) { | |
const evaluator = new XPathEvaluator(); | |
const document = node.ownerDocument?.documentElement ?? node.documentElement; | |
const resolver = evaluator.createNSResolver(document); | |
const results = evaluator.evaluate(expr, node, resolver, 0, null); | |
let result; | |
while (result = results.iterateNext()) { | |
yield result; | |
} | |
} | |
function queryXPath(node, expr){ | |
for (const result of queryXPathAll(node, expr)){ | |
return result; | |
} | |
} | |
// Process NPCs found in `node`. Emit raw data (or possibly actual Actors). | |
function processNPCs(node){ | |
let npcNodes = querySelectorAll(node, 'root>npc>*'); | |
for (const npcNode of npcNodes){ | |
yield processNPC(npcNode)); | |
} | |
} | |
function processNPC(npcNode){ | |
let npcData = { | |
name: querySelector(npcNode, 'name').innerHTML, | |
abilities: processAbilities(npcNode) | |
} | |
return npcData; | |
} | |
// Process NPC abilities found in `npcNode`. Return an array of ability data (or perhaps Items) | |
function processAbilities(npcNode){ | |
let powerNodes = Array.from(querySelectorAll(npcNode, 'powers')) | |
return powerNodes.map(processAbility); | |
} | |
function processAbility(powerNode){ | |
// ... | |
} | |
//// Main //// | |
const rawData = realRawData; | |
const data = new DOMParser().parseFromString(rawData, "text/xml"); | |
// Demonstration of XPath vs CSS Selectors | |
console.log(Array.from(queryXPathAll(data, '/root/npc/*'))); | |
console.log(Array.from(querySelectorAll(data, 'root>npc>*'))); | |
for (const npcNode of queryXPathAll(data, '/root/npc/*')){ | |
console.log(processNPC(npcNode)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment