Browse Source

Expose function for parsing only a page (i.e., root tag is <diagram>)

Joeri Exelmans 2 years ago
parent
commit
442334bb5f
1 changed files with 42 additions and 36 deletions
  1. 42 36
      drawio2py/parser.py

+ 42 - 36
drawio2py/parser.py

@@ -127,6 +127,46 @@ class Parser:
 
 			cell_dict[cell.id] = cell
 
+	@staticmethod
+	def parse_page(page):
+		# found = page.find("mxGraphModel")
+		# page
+		if len(page) == 0:
+			nroot = Parser.decode_and_deflate(page.text)
+		else:
+			nroot = page[0]
+		mxgm = nroot
+
+		cell_dict = {} # mapping from ID to cell
+		Parser.parse_components(mxgm[0], cell_dict)
+
+		# resolve parent/child, source/target references
+		root = None
+		for cell_id, cell in cell_dict.items():
+			parent_id = cell.parent # cell.parent will be overwritten with the actual cell
+			if parent_id == None:
+				root = cell
+			else:
+				cell_dict[parent_id].children.append(cell)
+				cell.parent = cell_dict[parent_id]
+			if isinstance(cell, Edge):
+				if cell.source:
+					cell_dict[cell.source].outgoing.append(cell)
+					cell.source = cell_dict[cell.source]
+				if cell.target:
+					cell_dict[cell.target].incoming.append(cell)
+					cell.target = cell_dict[cell.target]
+
+		if root == None:
+			raise Exception("No root cell in page " + str(px) + " (every cell had a parent)")
+
+		pg = Page(
+			id=page.attrib.get("id"),
+			name=page.attrib.get("name"),
+			attributes=mxgm.attrib,
+			root = root)
+		return pg
+
 	@staticmethod
 	def parse(filename):
 		"""Does the actual file parsing.
@@ -149,40 +189,6 @@ class Parser:
 		pages = root.findall(".//diagram")
 
 		for px, page in enumerate(pages):
-			if dfile.compressed:
-				nroot = Parser.decode_and_deflate(page.text)
-			else:
-				nroot = page[0]
-			mxgm = nroot
-
-			cell_dict = {} # mapping from ID to cell
-			Parser.parse_components(mxgm[0], cell_dict)
-
-			# resolve parent/child, source/target references
-			root = None
-			for cell_id, cell in cell_dict.items():
-				parent_id = cell.parent # cell.parent will be overwritten with the actual cell
-				if parent_id == None:
-					root = cell
-				else:
-					cell_dict[parent_id].children.append(cell)
-					cell.parent = cell_dict[parent_id]
-				if isinstance(cell, Edge):
-					if cell.source:
-						cell_dict[cell.source].outgoing.append(cell)
-						cell.source = cell_dict[cell.source]
-					if cell.target:
-						cell_dict[cell.target].incoming.append(cell)
-						cell.target = cell_dict[cell.target]
-
-			if root == None:
-				raise Exception("No root cell in page " + str(px) + " (every cell had a parent)")
-
-			pg = Page(
-				id=page.attrib.get("id", str(px)),
-				name=page.attrib.get("name", ""),
-				attributes=mxgm.attrib,
-				root = root)
-
-			dfile.pages.append(pg)
+			dfile.pages.append(Parser.parse_page(page))
+
 		return dfile