Skip to content

Commit

Permalink
add .text
Browse files Browse the repository at this point in the history
  • Loading branch information
pladaria committed Jun 28, 2016
1 parent fbac280 commit 5c05d2d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
13 changes: 13 additions & 0 deletions build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ var xmlQuery = function (ast) {
return node[name];
}
};
var text = function () {
var res = '';
each(function (node) {
if (node.type === 'text') {
res += node.value;
}
else {
res += xmlQuery(node).children().text();
}
});
return res;
};
return {
attr: attr,
children: children,
Expand All @@ -45,6 +57,7 @@ var xmlQuery = function (ast) {
map: map,
prop: prop,
size: size,
text: text,
};
};
module.exports = xmlQuery;
24 changes: 20 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,17 @@ const xmlQuery = (ast: XmlNode|XmlNode[]) => {
};

/**
* Returns a new XmlQuery for the selected element by index
* Returns a new XmlQuery object for the selected element by index
*/
const eq = (index: number) => xmlQuery(nodes[index]);

/**
* Returns a new XmlQuery for the first element
* Returns a new XmlQuery object for the first element
*/
const first = () => eq(0);

/**
* Returns a new XmlQuery for the last element
* Returns a new XmlQuery object for the last element
*/
const last = () => eq(length - 1);

Expand All @@ -101,13 +101,28 @@ const xmlQuery = (ast: XmlNode|XmlNode[]) => {
/**
* Get the value of a property for the first element in the set
*/
const prop = (name?: string) => {
const prop = (name: string) => {
const node = first();
if (node) {
return node[name];
}
};

/**
* Get the combined text contents of each element, including their descendants
*/
const text = () => {
let res = '';
each(node => {
if (node.type === 'text') {
res += node.value;
} else {
res += xmlQuery(node).children().text();
}
});
return res;
};

return {
attr,
children,
Expand All @@ -121,6 +136,7 @@ const xmlQuery = (ast: XmlNode|XmlNode[]) => {
map,
prop,
size,
text,
};
};

Expand Down
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,14 @@ test('children', t => {
});
reader.parse(xmlMessage1);
});

test('text', t => {
const reader = xmlReader.create();
reader.on('done', ast => {
const expected = 'AliceBobHelloThis is a demo!';
const result = xQuery(ast).text();
t.equal(result, expected, 'text is correct');
t.end();
});
reader.parse(xmlMessage1);
});

0 comments on commit 5c05d2d

Please sign in to comment.