Skip to content

Instantly share code, notes, and snippets.

@Varriount
Last active December 30, 2021 23:44
Show Gist options
  • Save Varriount/0069395761069e3bc7adb1569dab3f55 to your computer and use it in GitHub Desktop.
Save Varriount/0069395761069e3bc7adb1569dab3f55 to your computer and use it in GitHub Desktop.
// 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