Artit Satanakulpanich wrote:
> How can i search value from xml file such as I want to find from *pubdate *and
> return* **biblioentry
> *Please give me some source code for further study*
> **
> <?xml version="1.0" encoding="ISO-8859-15"?>
> <!DOCTYPE bibliography PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
>           "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
> <bibliography id="personal_identity">
>     <biblioentry id="FHIW13C-1234">
>       <author>
>         <firstname>Godfrey</firstname>
>         <surname>Vesey</surname>
>       </author>
>       <title>Personal Identity: A Philosophical Analysis</title>
>       <publisher>
>         <publishername>Cornell University Press</publishername>
>       </publisher>
>       <pubdate>1977</pubdate>
>    </biblioentry>

class String
  def xtag(s)
    scan( %r!
              < #{s}  (?: \s+ (  [^>]*  )  )? / >
              |
              < #{s}  (?: \s+ (  [^>]*  )  )? >
              ( .*? )  </ #{s} >
          !mx ).
      map{ |unpaired, attr, data|   h = { }
        attr = ( unpaired || attr )
        if attr
          attr.scan( %r!  ( \S+ ) = " ( [^"]* ) "  !x ){ |k,v|
            h[k] = v }
        end
        [ h, data ]
      }
  end
  def xshow( depth=0 )
    text = ""
    split( /<([^>]*)>/ ).each_with_index{ |s,i|
      if 0 == i % 2
        text = s.strip
      else
        indent = " " * ( depth * 2 )
        case
          when s[0,1] == "/"
            depth -= 1
            puts text.map{|x| indent + x.strip }  if text != ""
          when s[-1,1] == "/"
            puts indent + s
          else
            puts indent + s
            depth += 1
        end
      end
    }
  end
end

gets(nil).xtag("biblioentry").each { |attr,data|
  if data.xtag("pubdate")[0][1] > "1997"
    puts attr["id"]
    data.xshow( 1 )
  end
}

Output:

FHIW13C-1298-4
  author
    firstname
      Brian
    surname
      Garrett
  title
    Personal Identity and Self-Consciousness
  publisher
    publishername
      Routledge
  pubdate
    1998
FHIW13CX-1202-1
  author
    firstname
      John
    surname
      Perry
  title
    Identity, Personal Identity, and the Self
  publisher
    publishername
      Hackett
  pubdate
    2002