nautical nautical - 3 months ago 15
Linux Question

Get a specific element with xmllint

Consider the following HTML code as in file

example.html


<!DOCTYPE html>
<head>
<meta charset="utf-8">

<body>
<div class="container">
<h1>
<a href="/">
<img src="/images/image.png"/>
</a>
</h1>
<ul>
<li><a href="/" >link1<br /><span>content</span></a></li>
<li><a href="/folder" >link2<br /><span>more contend</span></a></li>
</ul>
</div><!-- .container -->
<div class="container">
<ul class="disc">
<li><strong>no interest 1</strong></li>
<li><strong>no interest 2</strong></li>
<li><strong>no interest 3</strong></li>
<li>keyword1: <strong>unkown_content</strong></li>
<li>keyword2: <strong>unkown_content</strong></li>
</ul>
</div><!-- .container -->
<div class="container">
<ul class="disc">
<li><a href="/folder1">not interested</a></li>
<li><a href="/folder2">not interested</a></li>
<li><a href="/folder3">not interested</a></li>
<li>keyword1: <strong>unkown_content</strong></li>
<li>keyword2: <strong>unkown_content</strong></li>
</ul>
</div><!-- .container -->
</body>
</html>


I would like to get the
unkown_content
after the second
keyword1
. I have
tried

xmllint --html --xpath "//li[text()='keyword1: ']" example.html 2>/dev/null
<li>keyword1: <strong>unkown_content</strong></li><li>keyword1: <strong>unkown_content</strong></li>


As you can see this returns both nodes with
keyword1
. How do I get the content of the last occurence?

Answer

Try xmllint --html --xpath "//li[text()='keyword1: '][last()]" example.html 2>/dev/null.

Note the addition of [last()] - it points to the last occurrence of //li[text()='keyword1: '].

If this doesn't work (I can't verify it at this moment), try:

xmllint --html --xpath "(//li[text()='keyword1: '])[last()]" example.html 2>/dev/null