ReXML & to_json

Does REXML support to_json? I keep getting "object references itself"
when I do this (simplified version):

    xml = Document.new("<root><ooh fert='nerdle'>Narf!</ooh></root>")

   @json = xml.to_json

Is it possible to output this xml as json.

The source xml is actually much larger, and I want to execute some
xpath on that, and return the results as json.

-S

Apparently not, but you can probably use Hash.from_xml, which parses
the XML into a hash using REXML and SimpleXML.

hash = Hash.from_xml("...")
json = hash.to_json

> Is it possible to output this xml as json.

> The source xml is actually much larger, and I want to execute some
> xpath on that, and return the results as json.

Apparently not, but you can probably use Hash.from_xml, which parses
the XML into a hash using REXML and SimpleXML.

hash = Hash.from_xml("...")
json = hash.to_json

Cheers Rick,

That works, trying to do the same with xml.elements(xpath) introduces
a new problem though, I feel I'm close to working it out, but it's
late, and I'm going to bed.

I'm trying to take a fairly large xml document (from a 3rd party url),
run an xpath query on it, then return those results as json to my
client side js.

I've been trying this approach:

sourceXml = Document.new(lots of xml)

xml = Document.new('<data/>')

xml.entities.each(xpath) { |e|
   xml.root.add e
}

Which works, but takes a very long time to complete. Is this the most
efficient way to do it? I might just create a hash right there, from
the attributes I'm interested in, rather than send the whole lot back.

-S

I've been trying this approach:

sourceXml = Document.new(lots of xml)

xml = Document.new('<data/>')

xml.entities.each(xpath) { |e|
   xml.root.add e

}

Which works, but takes a very long time to complete. Is this the most
efficient way to do it? I might just create a hash right there, from
the attributes I'm interested in, rather than send the whole lot back.

In the end I ditched rexml and went with the ruby libxml bindings to
speed things up. Then built a hash up with the results like this:

    @i = Hash.new

    elem = xml.find(xpath).each do |e|
      messageId = e.parent.parent['message_id']
      @i[messageId] = Hash.new
      @i[messageId]['summary'] = e.find_first('./element')['summary']
       .
       .
    end

The just call to_json on @i

Hopefully this will be usefull to anyone else doing the same kind of
thing.