LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Sorting specific values from an XML file (https://www.linuxquestions.org/questions/programming-9/sorting-specific-values-from-an-xml-file-833655/)

canimsin 09-21-2010 07:44 PM

Sorting specific values from an XML file
 
Hi, all.
I need a shell script which gathers the data from a remote XML file and then displays it according to my needs.. I need this for my job due to the fact that I need to keep track price changes of euro, usd, gold, etc.
The XML file I am talking about is located at this page: here.
The reason I am posting the URL is that I need to use curl to get this file and it does NOT have newlines after each tag. I thought that that would be a problem.
Here is what I need from the script:
1) curl to get the page
2) make use of sed, awk, etc. to display its contents in a more structured and readable manner as shown below:
A: 64.125 (% -0.26)
B: 81.130 (% -0.32)
C: 1.4930 (% 0.00)
D: 1.9590 (% 0.36)

I am looking forward to your insights..
Thanks!

alunduil 09-21-2010 08:00 PM

Is there a particular reason you have to use BASH rather than a scripting language like perl, python, or ruby? All of these languages have mechanisms for parsing XML and grabbing webpage contents that making writing such a utility much easier.

I'm not saying it's not possible in BASH just that it would require more than a simple little script.

Regards,

Alunduil

canimsin 09-21-2010 08:05 PM

perl and python are also welcome. There is no specific reason that I prefer shell scripting over those languages.. I also think that it is a really tough job to accomplish this task under bash even though I do not know a little bit on programming :)

kurumi 09-21-2010 08:29 PM

Code:

#!/usr/bin/env ruby -w

require 'net/http'
require 'rexml/document'
include REXML
url="http://cnnturk.com/finans/ticker/endeks.asp"
url=URI.parse(url)
response = Net::HTTP.get_response(url)
ret=response.body
xml= Document.new(ret)
xml.elements.each("Exchange/Content") do |element|
    print "Percent: #{element.attributes["Percent"]}, Price: #{element.attributes["Price"] }\n"
end


Code:

$ ruby test.rb
Percent: -0.26, Price: 64.125
Percent: -0.32, Price: 81.130
Percent: 0.00, Price: 1.4930
Percent: 0.36, Price: 1.9590


jschiwal 09-21-2010 08:35 PM

You could use xsltproc to transform the xml file according to your .xslt transform file.

Also, using 'xmllint --format' could reformat the xml file making it easier to use sed or awk if you wish to.

Kenhelm 09-21-2010 10:48 PM

Code:

curl -s http://cnnturk.com/finans/ticker/endeks.asp |
grep -o 'Content[^>]*' |
sed 's/[^0-9".-]//g
s/"\(.*\)""\(.*\)"".*/: \2 (% \1)/
1s/^/A/
2s/^/B/
3s/^/C/
4s/^/D/'

A: 64.125 (% -0.26)
B: 81.130 (% -0.32)
C: 1.4930 (% 0.00)
D: 1.9590 (% 0.36)



All times are GMT -5. The time now is 08:33 AM.