Sha256: 592e72569c9afdac2c3b318287fc2f2faad82fe0520d4dfb874117c086fe68f9

Contents?: true

Size: 1.23 KB

Versions: 19

Compression:

Stored size: 1.23 KB

Contents

# A simple xml parser. It is simple in the respect as that it doesn't address
# any of the complexities of XML. This is ruby 1.9.

$:.unshift File.dirname(__FILE__) + "/../lib"

require 'pp'
require 'parslet'

class XML < Parslet::Parser
  root :document
  
  rule(:document) {
    tag(close: false).as(:o) >> document.as(:i) >> tag(close: true).as(:c) |
    text
  }
  
  # Perhaps we could have some syntax sugar to make this more easy?
  #
  def tag(opts={})
    close = opts[:close] || false
    
    parslet = str('<')
    parslet = parslet >> str('/') if close
    parslet = parslet >> (str('>').absent? >> match("[a-zA-Z]")).repeat(1).as(:name)
    parslet = parslet >> str('>')
    
    parslet
  end
  
  rule(:text) {
    match('[^<>]').repeat(0)
  }
end

def check(xml)
  r = XML.new.parse(xml)

  # We'll validate the tree by reducing valid pairs of tags into simply the
  # string "verified". If the transformation ends on a string, then the
  # document was 'valid'. 
  #
  t = Parslet::Transform.new do
    rule(
      o: {name: simple(:tag)}, 
      c: {name: simple(:tag)}, 
      i: simple(:t)
    ) { 'verified' } 
  end

  t.apply(r)
end

pp check("<a><b>some text in the tags</b></a>")
pp check("<b><b>some text in the tags</b></a>")

Version data entries

19 entries across 19 versions & 3 rubygems

Version Path
parslet-2.0.0 example/simple_xml.rb
parslet-1.8.2 example/simple_xml.rb
parslet-1.8.1 example/simple_xml.rb
parslet-1.8.0 example/simple_xml.rb
swift-pyrite-0.1.1 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/simple_xml.rb
swift-pyrite-0.1.0 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/simple_xml.rb
parslet-1.7.1 example/simple_xml.rb
parslet-1.7.0 example/simple_xml.rb
parslet-1.6.2 example/simple_xml.rb
parslet-1.6.1 example/simple_xml.rb
parslet-1.6.0 example/simple_xml.rb
parslet-1.5.0 example/simple_xml.rb
ghazel-parslet-1.4.0.2 example/simple_xml.rb
ghazel-parslet-1.4.0.1 example/simple_xml.rb
parslet-1.4.0 example/simple_xml.rb
parslet-1.3.0 example/simple_xml.rb
parslet-1.2.3 example/simple_xml.rb
parslet-1.2.1 example/simple_xml.rb
parslet-1.2.0 example/simple_xml.rb