14

I'm writing a small script to learn how to parse an XHTML web page. The following command:

cat q?s=goog.xhtml | xpath '//span[@id="yfs_l10_goog"]'

returns:

Found 2 nodes:
-- NODE --
<span id="yfs_l10_goog">624.50</span>-- NODE --
<span id="yfs_l10_goog">624.50</span>

How do I:

  • need to write my command in order to only extract the value 624.50 ?

  • what do I need to do to extract it only once ?

source page I'm parsing: http://finance.yahoo.com/q?s=goog

3
  • This is more of an xpath question, isn't it? Commented Feb 13, 2011 at 14:44
  • yes indeed. I would like to get it working using xpath Commented Feb 13, 2011 at 16:33
  • updated post title to be clearer Commented Feb 13, 2011 at 16:41

1 Answer 1

18

Edit 2:

Give this a try:

xpath -q -e '//span[@id="yfs_l10_goog"][1]/text()'

Edit:

Pipe your output through:

sed -n '/span/{s/<span[^<]*>\([^<]*\)<.*/\1/;p;q}'

Original answer:

Using xmlstarlet:

echo -e '<foo><span id="yfs_l10_goog">624.50</span>\n<bar>xyz</bar><span id="yfs_l10_goog">555.50</span>\n<span id="yfs_l10_goog">123.50</span></foo>' | 
    xmlstarlet sel -t -v "//span[@id='yfs_l10_goog']"

Result of query:

624.50

Result of echo:

<foo><span id="yfs_l10_goog">624.50</span>
<bar>xyz</bar><span id="yfs_l10_goog">555.50</span>
<span id="yfs_l10_goog">123.50</span></foo>

Result of xml fo:

<?xml version="1.0"?>
<foo>
  <span id="yfs_l10_goog">624.50</span>
  <bar>xyz</bar>
  <span id="yfs_l10_goog">555.50</span>
  <span id="yfs_l10_goog">123.50</span>
</foo>

Other queries:

$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][1]"
624.50
$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][3]"
123.50
$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][last()]"
123.50
Sign up to request clarification or add additional context in comments.

9 Comments

Hi Dennis, i wish to use xpath.
@Baba: I think that utility has only very basic functionality. See my edited answer.
hmm, I believe xpath allows to be more direct by selecting nodes. w3schools have some examples but i have trouble simplifying them to match my requirements: w3schools.com/XPath/xpath_examples.asp
getting: Cannot open file '-q' at /usr/share/perl5/XML/XPath.pm line 53. not sure what it means
@Baba: Your version seems to be different than mine. Try it without the -q (and possibly without the -e).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.