MCPcopy Create free account
hub / github.com/NanGePlus/LightRAGTest / xml_to_json

Function xml_to_json

LightRAG/lightrag/utils.py:215–272  ·  view source on GitHub ↗
(xml_file)

Source from the content-addressed store, hash-verified

213
214
215def xml_to_json(xml_file):
216 try:
217 tree = ET.parse(xml_file)
218 root = tree.getroot()
219
220 # Print the root element's tag and attributes to confirm the file has been correctly loaded
221 print(f"Root element: {root.tag}")
222 print(f"Root attributes: {root.attrib}")
223
224 data = {"nodes": [], "edges": []}
225
226 # Use namespace
227 namespace = {"": "http://graphml.graphdrawing.org/xmlns"}
228
229 for node in root.findall(".//node", namespace):
230 node_data = {
231 "id": node.get("id").strip('"'),
232 "entity_type": node.find("./data[@key='d0']", namespace).text.strip('"')
233 if node.find("./data[@key='d0']", namespace) is not None
234 else "",
235 "description": node.find("./data[@key='d1']", namespace).text
236 if node.find("./data[@key='d1']", namespace) is not None
237 else "",
238 "source_id": node.find("./data[@key='d2']", namespace).text
239 if node.find("./data[@key='d2']", namespace) is not None
240 else "",
241 }
242 data["nodes"].append(node_data)
243
244 for edge in root.findall(".//edge", namespace):
245 edge_data = {
246 "source": edge.get("source").strip('"'),
247 "target": edge.get("target").strip('"'),
248 "weight": float(edge.find("./data[@key='d3']", namespace).text)
249 if edge.find("./data[@key='d3']", namespace) is not None
250 else 0.0,
251 "description": edge.find("./data[@key='d4']", namespace).text
252 if edge.find("./data[@key='d4']", namespace) is not None
253 else "",
254 "keywords": edge.find("./data[@key='d5']", namespace).text
255 if edge.find("./data[@key='d5']", namespace) is not None
256 else "",
257 "source_id": edge.find("./data[@key='d6']", namespace).text
258 if edge.find("./data[@key='d6']", namespace) is not None
259 else "",
260 }
261 data["edges"].append(edge_data)
262
263 # Print the number of nodes and edges found
264 print(f"Found {len(data['nodes'])} nodes and {len(data['edges'])} edges")
265
266 return data
267 except ET.ParseError as e:
268 print(f"Error parsing XML file: {e}")
269 return None
270 except Exception as e:
271 print(f"An error occurred: {e}")
272 return None

Callers 2

convert_xml_to_jsonFunction · 0.90
convert_xml_to_jsonFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected