Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Parse XPath #6470

Merged
merged 5 commits into from Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/util/tXml.js
Expand Up @@ -735,6 +735,34 @@ shaka.util.TXml = class {
}


/**
* Parse xPath strings for segments and id targets.
* @param {string} exprString
* @return {!Array<!shaka.util.TXml.PathNode>}
*/
static parseXpath(exprString) {
const returnPaths = [];
// Split string by paths but ignore '/' in quotes
const paths = exprString
.split(/\/+(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/);
for (const path of paths) {
const nodeName = path.match(/\b([A-Z])\w+/);

// We only want the id attribute in which case
// /'(.*?)'/ will suffice to get it.
const idAttr = path.match(/(@id='(.*?)')/);
if (nodeName) {
returnPaths.push({
name: nodeName[0],
id: idAttr ?
idAttr[0].match(/'(.*?)'/)[0].replaceAll('\'', '') : null,
});
}
}
return returnPaths;
}


/**
* Converts a tXml node to DOM element.
* @param {shaka.extern.xml.Node} node
Expand Down Expand Up @@ -775,3 +803,12 @@ shaka.util.TXml = class {
};

shaka.util.TXml.knownNameSpaces_ = new Map([]);


/**
* @typedef {{
* name: string,
* id: ?string
* }}
*/
shaka.util.TXml.PathNode;
tykus160 marked this conversation as resolved.
Show resolved Hide resolved
21 changes: 21 additions & 0 deletions test/util/tXml_unit.js
Expand Up @@ -416,4 +416,25 @@ describe('tXml', () => {
expect(TXml.parseFloat(HUGE_NUMBER_STRING)).toBe(Infinity);
expect(TXml.parseFloat('-' + HUGE_NUMBER_STRING)).toBe(-Infinity);
});

it('parseXpath', () => {
expect(TXml.parseXpath('/MPD')).toEqual([{name: 'MPD', id: null}]);
expect(TXml.parseXpath('/MPD/@type'))
.toEqual([{name: 'MPD', id: null}]);

const timelinePath = '/' + [
'MPD',
'Period[@id=\'6469\']',
'AdaptationSet[@id=\'7\']',
'SegmentTemplate',
'SegmentTimeline',
].join('/');
expect(TXml.parseXpath(timelinePath)).toEqual([
{name: 'MPD', id: null},
{name: 'Period', id: '6469'},
{name: 'AdaptationSet', id: '7'},
{name: 'SegmentTemplate', id: null},
{name: 'SegmentTimeline', id: null},
]);
});
});