Sha256: 39ebb93db24e4269183c6d0241a1d14e102ae2764d517e1b6cc0f9b2572a4ed8

Contents?: true

Size: 1.26 KB

Versions: 3

Compression:

Stored size: 1.26 KB

Contents

require 'xml/xxpath'

d=REXML::Document.new <<EOS
  <foo>
    <bar>
      <baz key="work">Java</baz>
      <baz key="play">Ruby</baz>
    </bar>
    <bar>
      <baz key="ab">hello</baz>
      <baz key="play">scrabble</baz>
      <baz key="xy">goodbye</baz>
    </bar>
    <more>
      <baz key="play">poker</baz>
    </more>
  </foo>
EOS


####read access
path=XML::XXPath.new("/foo/bar[2]/baz")

## path.all(document) gives all elements matching path in document
path.all(d)
=> [<baz key='ab'> ... </>, <baz key='play'> ... </>, <baz key='xy'> ... </>]

## loop over them
path.each(d){|elt| puts elt.text}
hello
scrabble
goodbye
=> [<baz key='ab'> ... </>, <baz key='play'> ... </>, <baz key='xy'> ... </>]

## the first of those
path.first(d)
=> <baz key='ab'> ... </>

## no match here (only three "baz" elements)
path2=XML::XXPath.new("/foo/bar[2]/baz[4]")
path2.all(d)
=> []

## "first" raises XML::XXPathError in such cases...
path2.first(d)
XML::XXPathError: path not found: /foo/bar[2]/baz[4]
	from ../lib/xml/../xml/xxpath.rb:130:in `first'

##...unless we allow nil returns
path2.first(d,:allow_nil=>true)
=> nil

##attribute nodes can also be returned
keysPath=XML::XXPath.new("/foo/*/*/@key")

keysPath.all(d).map{|attr|attr.text}
=> ["work", "play", "ab", "play", "xy", "play"]

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
pdf-labels-1.0.0 vendor/xml-mapping/examples/xpath_usage.intout
xml-mapping-0.8 examples/xpath_usage.intout
xml-mapping-0.8.1 examples/xpath_usage.intout