Class: Graphml2Json

Inherits:
Object
  • Object
show all
Defined in:
lib/graphml2json/graphml2json.rb

Class Method Summary collapse

Class Method Details

.generate(xml_string) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/graphml2json/graphml2json.rb', line 6

def self.generate(xml_string) 
  doc = Nokogiri::XML(xml_string)
  graph = doc.xpath('//xmlns:graph')
  nodes = graph.xpath('//xmlns:node')
  edges = graph.xpath('//xmlns:edge')

  @mapping = {}
  @json_nodes = []

  @graph = {}
  @graph[:nodes] = [] 
  @graph[:edges] = [] 

  nodes.each_with_index do |n, index|
    @mapping[n[:id]] = index 
    @graph[:nodes] << {:name => index}
  end

  @json_edges = [] 
  edges.each do |e|
    source = @mapping[e[:source]]
    target = @mapping[e[:target]]
    @graph[:edges] << { :source => source, :target => target }
  end

  JSON.generate(@graph)
end