Statistics
| Branch: | Tag: | Revision:

one / src / datastore_mad / remotes / xpath.rb @ ef25a754

History | View | Annotate | Download (2.33 KB)

1
#!/usr/bin/env ruby
2

    
3
# -------------------------------------------------------------------------- */
4
# Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                #
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may    */
6
# not use this file except in compliance with the License. You may obtain    */
7
# a copy of the License at                                                   */
8
#                                                                            */
9
# http://www.apache.org/licenses/LICENSE-2.0                                 */
10
#                                                                            */
11
# Unless required by applicable law or agreed to in writing, software        */
12
# distributed under the License is distributed on an "AS IS" BASIS,          */
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
14
# See the License for the specific language governing permissions and        */
15
# limitations under the License.                                             */
16
# -------------------------------------------------------------------------- */
17

    
18
#
19
# Simple command to parse an XML document (b64 encoded) and return one or more
20
# elements (refer by xpath)
21
#
22
require 'base64'
23
require 'rexml/document'
24
require 'getoptlong'
25
require 'pp'
26

    
27
opts = opts = GetoptLong.new(
28
    [ '--stdin',   '-s', GetoptLong::NO_ARGUMENT ],
29
    [ '--base64',  '-b', GetoptLong::REQUIRED_ARGUMENT ]
30
)
31

    
32
source = :stdin
33
tmp64  = ""
34

    
35
begin
36
    opts.each do |opt, arg|
37
        case opt
38
            when '--stdin'
39
                source = :stdin
40
            when '--base64'
41
                source = :b64
42
                tmp64  = arg
43
        end
44
    end
45
rescue Exception => e
46
    exit(-1)
47
end
48

    
49
values = ""
50

    
51
case source
52
when :stdin
53
    tmp = STDIN.read
54
when :b64
55
    tmp = Base64::decode64(tmp64)
56
end
57

    
58
xml = REXML::Document.new(tmp).root
59

    
60
ARGV.each do |xpath|
61
    if xpath.match(/^%m%/)
62
        xpath = xpath[3..-1]
63
        ar = xml.elements.to_a(xpath).map {|t| t.text }
64
        values << ar.join(' ')
65
    else
66
        element = xml.elements[xpath.dup]
67
        if !element.nil?
68
            if element.class.method_defined?(:text)
69
                values << ( element.text || '' )
70
            else
71
                values << ( element.to_s || '' )
72
            end
73
        end
74
    end
75
    values << "\0"
76
end
77

    
78
puts values
79

    
80
exit 0