Navigate SVG – Aspose.SVG for Python via .NET

Inspecting the contents of SVG files is often necessary to extract information about the file, its elements, and their hierarchy. Aspose.SVG for Python via the .NET API is fully compliant with the official SVG specifications and provides extensive functionality for working with the SVG Document Object Model (DOM). This API supports a wide range of navigation and inspection capabilities for SVG content.

In this article, you will learn:

To continue following this tutorial, you should install and configure the Aspose.SVG for Python via .NET library in your Python project. Our code examples help you to create, load, and read SVG files using the Python library.

View SVG Content

The easiest way to inspect the document content is to look at content as a string. The properties inner_html and outer_html of the Element class return a fragment of XML (or HTML) that represents the element and its contents. They are developed precisely for viewing SVG content as a string. The following Python code example shows how to view the content of an SVG file in the console:

  1. Define the full path to the SVG file you want to load.
  2. Use the SVGDocument class to load the SVG file from the specified path.
  3. Retrieve the outer HTML of the document’s root element using the outer_html property.
  4. Print the HTML content of the SVG document to the console to view its structure and content.
 1using Aspose.Svg;
 2using System.IO;
 3...
 4import os
 5from aspose.svg import *
 6
 7# Setup directories
 8data_dir = "data/"
 9document_path = os.path.join(data_dir, "document.svg")
10
11# Load an SVG document
12with SVGDocument(document_path) as document:
13    html = document.document_element.outer_html
14
15    print(html)
16# View the document content

The Document Object Model (DOM) is critical in navigating SVG files by providing a structured view of document elements and their relationships. It provides programmatic access to SVG elements and attributes, allowing detailed inspection and manipulation. Through the DOM, developers can navigate the SVG structure using methods to select elements by tag name, class, or ID. They can also use CSS selectors and XPath queries to find specific elements efficiently. This hierarchical model makes it easy to read and modify SVG content, get detailed information about specific elements, and interact with SVG flexibly and powerfully.

Extract Information about Specific SVG Element

The following example shows how to extract information about a particular SVG element from a file shapes.svg. This code snippet demonstrates how to load an SVG document, iterate through specific elements (<rect> in this case), and safely access and print their attributes:

  1. Adjust the input_path variable to point to your actual SVG file location.
  2. Use the SVGDocument(input_path) constructor to load an SVG file from the specified input_path.
  3. Use get_elements_by_tag_name(“rect”) method to iterate through all <rect> elements in the SVG document.
  4. Print the tag name and ID of each <rect> element.
 1fimport os
 2from aspose.svg import *
 3
 4# Prepare a path to the source and output SVG file
 5data_dir = "data/"
 6input_path = os.path.join(data_dir, "shapes.svg")
 7
 8# Load the SVG document
 9document = SVGDocument(input_path)
10
11# Iterate over elements in the SVG document
12for element in document.get_elements_by_tag_name("rect"):
13    print(f"Element: {element.tag_name}, ID: {element.id}")
14
15# Print attributes of the element
16    attributes = element.attributes
17    for i in range(attributes.length):
18        attr = attributes[i]
19        if attr is not None:
20            print(f" Attribute: {attr.name} = {attr.value}")

After running this example you will get the following result:

 1Element: rect, ID: first-rect
 2  Attribute: id = first-rect
 3  Attribute: x = 50
 4  Attribute: y = 90
 5  Attribute: width = 100
 6  Attribute: height = 90
 7  Attribute: style = stroke-width:5; stroke:FireBrick
 8Element: rect, ID: second-rect
 9  Attribute: id = second-rect
10  Attribute: x = 120
11  Attribute: y = 150
12  Attribute: width = 120
13  Attribute: height = 120
14  Attribute: style = stroke-width:10; stroke:DarkCyan
15Element: rect, ID: third-rect
16  Attribute: id = third-rect
17  Attribute: x = 170
18  Attribute: y = 220
19  Attribute: width = 90
20  Attribute: height = 90
21  Attribute: style = stroke-width:5; stroke:FireBrick

Inspection of an SVG Document and its Elements

Aspose.SVG contains a list of methods that are based on the Element Traversal Specifications. You can perform a detailed inspection of the document and its elements using the API. The following code sample shows the generalized usage of Element Traversal features.

Here’s the Python code that loads an SVG document ( shapes.svg), navigates through its elements, and prints the tag names:

 1import os
 2from aspose.svg import *
 3
 4# Setup directories
 5data_dir = "data/"
 6document_path = os.path.join(data_dir, "shapes.svg")
 7
 8# Load a document
 9with SVGDocument(document_path) as document:
10    # Get the root element
11    element = document.document_element
12    print(element.tag_name)  # svg
13
14    # Get the last child element of the root (which should be a <g> element)
15    element = element.last_element_child
16    print(element.tag_name)  # g
17
18    # Get the first child element of the <g> element (which should be a <rect> element)
19    element = element.first_element_child
20    print(element.tag_name)  # rect
  1. The <svg> element is a container, and it is used as the outermost element of SVG documents. To point the <svg> element, you use the document_element property of the SVGDocument class gives direct access to the <svg> element of the document. In the code snippet above, we use this way.
  2. The last_element_child property returns the last child element node of this element. In the example above, it is the <g> element.
  3. According to the code snippet above, the first_element_child property returns the first child of the <g> element. It is the <rect> element.

Edit SVG Using CSS Selector

Aspose.SVG for Python via .NET also implements CSS Selector specification that allows you to navigate over the document by using CSS like style.

The query_selector(selector) method of the Element class allows you to get the first element within the document that matches the specified selector. The query_selector_all(selector) method takes as a parameter the query selector and returns a NodeList of all the elements, which match the selector. With the resulting elements, you can make various manipulations: change its text, attributes, CSS styles, and so on.

In the following example, we use the query_selector() method to navigate an SVG document and search for the needed element for editing purposes:

 1import os
 2from aspose.svg import *
 3
 4# Setup directories
 5output_dir = "output/"
 6data_dir = "data/"
 7
 8document_path = os.path.join(data_dir, "shapes.svg")
 9
10# Load an SVG document from the file
11document = SVGDocument(document_path)
12
13# Get root svg element of the document
14svg_element = document.root_element
15
16# Get circle element to change color
17circle_element = svg_element.query_selector("circle")
18
19# Set a new "fill" attribute value for the circle element
20circle_element.set_attribute("stroke", "DarkCyan")
21
22# Save the SVG document to a file
23output_path = os.path.join(output_dir, "circle-color.svg")
24document.save(output_path)

On the figure: the source picture (a) and the edited picture (b).

Text “Original and edited images”

XPath Query ( XML Path Language), often referred to simply as an XPath, is a query language used to query data from documents. It is based on a DOM representation of the SVG document and selects nodes by various criteria. The syntax of the XPath expressions is quite simple, and what is more important, it is easy to read and support.

Aspose.SVG also has powerful XPath Specifications implementation along with Traversal Specifications. XPath queries are mainly made using the Document class’s evaluate() method. The evaluate(expression, contextNode, resolver, type, result) method accepts an XPath expression and other given parameters and returns a result of the specified type. This empowers you to use XPath Query to navigate over the document ( shapes.svg) as shown in the following code sample:

 1import os
 2from aspose.svg import *
 3from aspose.svg.dom.xpath import XPathResultType
 4
 5# Setup directories
 6output_dir = "output/"
 7data_dir = "data/"
 8if not os.path.exists(output_dir):
 9    os.makedirs(output_dir)
10
11# Prepare a path to a file loading
12document_path = os.path.join(data_dir, "shapes.svg")
13
14# Load an SVG document from the file
15document = SVGDocument(document_path)
16
17# Evaluate XPath expression
18xpath_expression = "//rect[@x='120']"
19xpath_result = document.evaluate(xpath_expression, document, None, XPathResultType.ANY, None)
20
21# Get the next evaluated node and print its parent_element
22node = xpath_result.iterate_next()
23if node:
24    print(node.parent_element)

See Also

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.