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
33
34
35
36
37
38
|
# File 'lib/graphml2json.rb', line 6
def self.generate(xml_string)
doc = Nokogiri::XML(xml_string)
doc.remove_namespaces!
graph = doc.xpath('//graph')
nodes = graph.xpath('//node')
edges = graph.xpath('//edge')
@mapping = {}
@json_nodes = []
@graph = {}
@graph[:nodes] = []
@graph[:edges] = []
nodes.each_with_index do |n, index|
attributes = data_attributes(n)
@mapping[n[:id]] = index
new_node = {:name => index}.merge(attributes)
@graph[:nodes] << new_node
end
@json_edges = []
edges.each do |e|
source = @mapping[e[:source]]
target = @mapping[e[:target]]
attributes = data_attributes(e)
new_edge = { :source => source, :target => target }.merge(attributes)
@graph[:edges] << new_edge
end
JSON.generate(@graph)
end
|