Get Elements By Attribute Value
I am sending a request via webservices in Javascript and the response i am receiving is like this: ACIA-11QWTKX
Solution 1:
You can use XPath with an expression like //Book[ListOfBookUser/BookUser]
:
var xmlMarkup = `<ListOfBook>
<Book>
<Id>ACIA-11QWTKX</Id>
<ListOfBookUser recordcount="0" lastpage="true">
</ListOfBookUser>
</Book>
<Book>
<Id>ACIA-ANC0CC</Id>
<ListOfBookUser recordcount="1" lastpage="true">
<BookUser>
<BookId>ACIA-ANC0CC</BookId>
<BookName>TKSP_GLOBAL</BookName>
</BookUser>
</ListOfBookUser>
</Book>
<Book>
<Id>ACIA-ANC0CF</Id>
<ListOfBookUser recordcount="0" lastpage="true">
</ListOfBookUser>
</Book>
<Book>
<Id>ACIA-EUMCH5</Id>
<ListOfBookUser recordcount="1" lastpage="true">
<BookUser>
<BookId>ACIA-EUMCH5</BookId>
<BookName>TKSP_MADRID_CENTRO_SUR</BookName>
</BookUser>
</ListOfBookUser>
</Book>
</ListOfBook>`;
var xmlDoc = newDOMParser().parseFromString(xmlMarkup, 'application/xml');
var bookSnapshot = xmlDoc.evaluate('//Book[ListOfBookUser/BookUser]', xmlDoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, l = bookSnapshot.snapshotLength; i < l; i++) {
var book = bookSnapshot.snapshotItem(i);
var id = xmlDoc.evaluate('Id', book, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (id != null) {
console.log(id.textContent);
}
}
For brevity of the sample, I have used the multi-line string literal delimiters `` only implemented in actual browsers, but the XPath API is supported in DOM implementations in Mozilla, Chrome, Safari and Edge.
Solution 2:
Using xpath
you can do this to extract all Book
elements that have BookUser
descendants (you need to look for descendants not for children, since your BookUsers
are contained inside ListOfBookUser
tags:
//Book[descendant::BookUser]
or
//Book[.//BookUser]
or (as @MartinHonnen showed in the comments):
//Book[ListOfBookUser/BookUser]
Solution 3:
Try to see:
[MDN]https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
[W3Schools] : http://www.w3schools.com/xsl/xpath_examples.asp
.evaluate function is usefull.
Post a Comment for "Get Elements By Attribute Value"