[Solved] get elements by attribute value


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 = new DOMParser().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.

0

solved get elements by attribute value