Inspect and Navigate SVG in C#

Before code changes colors, replaces shapes, extracts data, or converts an SVG document, it often needs to find the exact element to work with. Aspose.SVG for .NET gives C# code DOM access to SVG content, so you can inspect markup, move through the document tree, select elements with CSS selectors, evaluate XPath queries, and iterate through nodes with custom filters.

In this article, you will learn how to:

Quick Start: Find an SVG Element in C#

The following example loads an SVG file, finds the first <rect> element with a CSS selector, and prints the element markup:

 1using System;
 2using System.IO;
 3using Aspose.Svg;
 4using Aspose.Svg.Dom;
 5
 6string inputPath = Path.Combine(DataDir, "shapes.svg");
 7
 8using (SVGDocument document = new SVGDocument(inputPath))
 9{
10    // Find the first rectangle in the SVG document
11    Element rectangle = document.QuerySelector("rect");
12
13    if (rectangle == null)
14    {
15        Console.WriteLine("No <rect> element was found.");
16        return;
17    }
18
19    // Print the selected element as SVG markup
20    Console.WriteLine(rectangle.OuterHTML);
21}

Use this pattern when you already know which element you need to inspect or modify. The null check keeps the example clear when the input SVG does not contain the expected element. If the SVG structure is unknown, start with DOM traversal or OuterHTML to understand the document first.

View SVG Markup as a String

The OuterHTML property returns the markup of an element together with its children. The InnerHTML property returns only the element content. These properties are useful for quick diagnostics, logging, and checking which part of the SVG document has been selected.

This example prints the markup of the root <svg> element:

1using Aspose.Svg;
2using System;
 1// View SVG document content as OuterHTML in C#
 2
 3// Load an SVG document
 4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "bezier-curves.svg")))
 5{
 6    // Use the OuterHTML property
 7    string html = document.DocumentElement.OuterHTML;
 8
 9    Console.WriteLine(html);
10}
11// View the document content

An SVG document is an XML-based tree of nodes. The root <svg> element can be accessed in two common ways:

1using Aspose.Svg;
2using Aspose.Svg.Dom;
3
4Element documentElement = document.DocumentElement;
5SVGSVGElement rootElement = document.RootElement;

For simple traversal inside the SVG element tree, use element-level properties such as FirstElementChild, LastElementChild, NextElementSibling, and Children. Here, Children means the child elements of an Element, for example the children of <svg> or <g>, not the Document.Children collection. The following example walks from the document element to nested child elements and prints their tag names:

1using Aspose.Svg;
2using System;
3using System.IO;
 1// Traverse SVG document elements using the DOM in C#
 2
 3// Load an SVG document
 4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes_svg.svg")))
 5{
 6    // Get direct access to the <svg> element of the document
 7    Element element = document.DocumentElement;
 8    Console.WriteLine(element.TagName); // svg
 9
10    // Use the LastElementChild property
11    element = element.LastElementChild;
12    Console.WriteLine(element.TagName); // g
13
14    // Use the FirstElementChild property
15    element = element.FirstElementChild;
16    Console.WriteLine(element.TagName); // rect
17}

Find Elements by Tag Name

Use GetElementsByTagName() when you need all descendants with the same SVG tag name, such as all <circle> or <rect> elements. The method returns a NodeList, which can be inspected or filtered in code.

The following example finds the first <g> element, reads its first child element, and prints the width and height of that <rect> element:

1using Aspose.Svg;
2using System;
3using System.IO;
4using System.Linq;
 1// Extract information about a specific SVG element in C#
 2
 3string documentPath = Path.Combine(DataDir, "shapes_svg.svg");
 4
 5// Load a document from a file
 6using (SVGDocument document = new SVGDocument(documentPath))
 7{
 8    // Get the root <svg> element of the document
 9    Element svg = document.DocumentElement;
10
11    // Find the first child element with a given tag name
12    SVGGElement g = svg.GetElementsByTagName("g").First() as SVGGElement;
13    SVGRectElement rect = g.FirstElementChild as SVGRectElement;
14
15    Console.WriteLine("Height: {0}", rect.Height); // 100
16    Console.WriteLine("Width: {0}", rect.Width); // 100
17}

Find SVG Elements with CSS Selectors

CSS selectors are often the most concise way to find elements by tag name, id, class, attributes, or position in the SVG tree. QuerySelector() returns the first matching element. QuerySelectorAll() returns all matching elements as a NodeList.

The following example uses an attribute selector to find only the rectangles whose inline style contains FireBrick, then prints their id values. This is a more targeted search than selecting every <rect> element in the file.

 1using System;
 2using System.IO;
 3using Aspose.Svg;
 4using Aspose.Svg.Collections;
 5using Aspose.Svg.Dom;
 6
 7string inputPath = Path.Combine(DataDir, "shapes.svg");
 8
 9using (SVGDocument document = new SVGDocument(inputPath))
10{
11    // Select only rectangles whose style attribute contains "FireBrick"
12    NodeList fireBrickRectangles = document.QuerySelectorAll("rect[style*='FireBrick']");
13
14    if (fireBrickRectangles.Length == 0)
15    {
16        Console.WriteLine("No rectangles with FireBrick in the style attribute were found.");
17        return;
18    }
19
20    foreach (Element rectangle in fireBrickRectangles)
21    {
22        Console.WriteLine(rectangle.GetAttribute("id"));
23    }
24}

If the input SVG contains rectangles with FireBrick in the style attribute, the example prints their id values. The explicit empty-result check keeps the example useful when the SVG does not contain matching elements.

CSS selectors are also useful before editing. For larger examples that select owl illustration elements and modify them, see Edit SVG Using CSS Selectors.

XPath is useful when the selection condition is easier to express as a document query, for example by matching an attribute value or a hierarchy of elements. Aspose.SVG supports XPath evaluation through Evaluate().

The following example finds a <rect> element whose x attribute equals 120 and prints the selected node:

 1using System;
 2using System.IO;
 3using Aspose.Svg;
 4using Aspose.Svg.Dom;
 5using Aspose.Svg.Dom.XPath;
 6
 7string inputPath = Path.Combine(DataDir, "shapes.svg");
 8
 9using (SVGDocument document = new SVGDocument(inputPath))
10{
11    // Evaluate the XPath expression against the SVG document
12    IXPathResult result = document.Evaluate(
13        "//rect[@x='120']",
14        document,
15        null,
16        Dom.XPath.XPathResultType.Any,
17        null);
18
19    // Read the first matching node
20    Element selectedElement = result.IterateNext() as Element;
21
22    if (selectedElement == null)
23    {
24        Console.WriteLine("No rectangle with x=\"120\" was found.");
25        return;
26    }
27
28    Console.WriteLine(selectedElement.OuterHTML);
29}

In the sample shapes.svg file, this XPath expression selects the rectangle with id="second-rect". XPath is especially helpful when the condition is attribute-based or when the target element is easier to describe by its position in the XML tree.

Filter Nodes with NodeIterator

Use CreateNodeIterator() when traversal should move through the document while a custom filter decides which nodes are accepted. A filter derived from NodeFilter returns FILTER_ACCEPT for nodes that should be visible to the iterator and FILTER_REJECT for nodes that should be skipped.

The following example creates an iterator that accepts only <rect> elements:

1using Aspose.Svg;
2using Aspose.Svg.Dom;
3using Aspose.Svg.Dom.Traversal.Filters;
4using System;
5using System.IO;
 1// Iterate SVG rectangle nodes with a custom NodeFilter in C#
 2
 3using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
 4{
 5    // Create a node iterator
 6    using (INodeIterator iterator = document.CreateNodeIterator(document, NodeFilter.SHOW_ALL, new RectFilter()))
 7    {
 8        Node node;
 9        while ((node = iterator.NextNode()) != null)
10        {
11        }
12    }
13}

The RectFilter class accepts nodes whose NodeName is rect:

1public class RectFilter : NodeFilter
2{
3    public override short AcceptNode(Node node)
4    {
5        return string.Equals("rect", node.NodeName)
6            ? FILTER_ACCEPT
7            : FILTER_REJECT;
8    }
9}

NextNode() returns the next accepted node and advances the iterator position. This is useful when you need a repeatable traversal rule rather than a one-time selector.

FAQ

1. Should I use CSS selectors or XPath to find SVG elements?
Use CSS selectors for common SVG selection tasks such as finding elements by tag name, id, class, attributes, or parent-child relationships. Use XPath when the query is easier to express as a document path or when you need more XML-style selection logic.

2. What is the difference between DocumentElement and RootElement?
DocumentElement comes from the general DOM Document API and returns the document element as an Element. RootElement is specific to SVGDocument and returns the root <svg> element as SVGSVGElement, which exposes SVG-specific members.

3. Can I inspect SVG before editing or converting it?
Yes. A common workflow is to load an SVG file, inspect its structure with OuterHTML, DOM traversal, CSS selectors, or XPath, and only then modify selected elements or pass the document to conversion code.

4. Can I inspect the generated or edited SVG without saving it first?
Yes. After creating or editing an SVGDocument, read DocumentElement.OuterHTML or inspect selected elements directly in memory. Saving is only needed when you want to write the document to a file, stream, or another storage target.

Next Steps