Finding all paths in an XML document

G

Ghislain Mary

Hi all,

I'd like to know how you would search for all the paths of an XML
document using REXML. For example, let say that the document is the
following:

<document>
<content>a simple sample</content>
<node>
<content>some text</content>
</node>
<node>
<foo>
<content>an other sample</content>
</foo>
</node>
</document>

What I'd like to have is an Array like this:
[['content'],
['node'],
['node', 'content'],
['node', 'foo'],
['node', 'foo', 'content']]

Any ideas ?

Thanks,

Ghislain
 
R

Robert Klemme

Ghislain said:
Hi all,

I'd like to know how you would search for all the paths of an XML
document using REXML. For example, let say that the document is the
following:

<document>
<content>a simple sample</content>
<node>
<content>some text</content>
</node>
<node>
<foo>
<content>an other sample</content>
</foo>
</node>
</document>

What I'd like to have is an Array like this:
[['content'],
['node'],
['node', 'content'],
['node', 'foo'],
['node', 'foo', 'content']]

Any ideas ?

Thanks,

Ghislain

This might help:

require "rexml/document"

doc = File.open( "doc.xml" ){|io| REXML::Document.new io}

doc.elements.each( "//*" ) do |el|
p el.xpath.split(%r{/})
end

Alternative:

require "rexml/document"

doc = File.open( "doc.xml" ){|io| REXML::Document.new io}

doc.elements.each "//*" do |el|
path = []
par = el

while par
path.unshift par.name
par = par.parent
end

path.shift
p path
end

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top