Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
This article shows how to change SVG styles programmatically in C#: update fill and stroke, rewrite inline style attributes, remove blocking styles from design-tool exports, and add global CSS rules before rendering or converting SVG files.
You will learn how to:
fill or stroke.style attributes when they block your changes.<style> element for consistent styling.In real-world workflows, SVG files are rarely authored for programmatic processing. They are typically produced by design tools, third-party services, or user uploads and contain a mix of styling mechanisms:
style attributes – highest priority<style> element or resolvable stylesheet – medium priorityfill, stroke) – lowest priorityThese mechanisms do not have equal priority. The normal priority order is inline styles → CSS rules → presentation attributes. If this is not taken into account, programmatic style changes may appear to not work even though the code executes correctly. Before changing anything, it is crucial to understand where styles come from and which ones take precedence. If you’re not familiar with SVG styling models, see SVG CSS vs Inline Styles vs Presentation Attributes in C#.
This guide focuses on DOM-level style modification with Aspose.SVG for .NET. For a broader troubleshooting guide, including font and conversion issues, see Common SVG Styling and Font Issues in C#.
| Goal | Recommended approach | Use when |
|---|---|---|
| Change one property and preserve the rest | Rewrite selected declarations inside the style attribute | Imported SVGs contain important inline styles |
| Remove style conflicts from generated SVG | Remove inline style attributes | You will replace them with CSS rules or presentation attributes |
| Apply one visual rule to many elements | Insert a global <style> element | You need consistent styling for text, shapes, or groups |
| Make simple DOM updates | Set presentation attributes like fill or stroke | The SVG is generated or controlled by your code |
If an SVG element has an inline style attribute, changing CSS rules or presentation attributes will not affect rendering. Therefore, every style change process should begin by checking inline styles. Using Aspose, you can inspect your document and identify where inline styles are used to inform your future strategy for changing and applying styles.
1using Aspose.Svg.Dom;
2using System.IO; 1// Find SVG elements that use inline style attributes in C#
2
3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
4
5// Select all elements that have inline style attributes
6var styledNodes = document.QuerySelectorAll("[style]");
7
8Console.WriteLine($"Found {styledNodes.Length} element(s) with inline styles:\n");
9
10foreach (var node in styledNodes)
11{
12 var element = (Element)node;
13
14 // Get and display the style attribute value
15 string styleValue = element.GetAttribute("style");
16 Console.WriteLine($"Element: <{element.TagName}>");
17 Console.WriteLine($"Style: {styleValue}\n");
18}After running the example, you will gain information about all inline style attributes and decide how to modify a particular element’s style to avoid conflicts.
1 Element: <line>
2 Style: stroke:grey; stroke-width:5
3
4 Element: <polygon>
5 Style: fill:orange; stroke:purple; stroke-width:1; fill-opacity:1
6
7 Element: <ellipse>
8 Style: fill:orangeredWhy this matters
style attributes override all other styling mechanisms.style attributes.Avoid removing all inline styles when:
<style> element or presentation attributes, removal will cause loss of formatting.Instead of deleting inline style attributes blindly, you can read, modify, and rewrite them. To modify inline styles safely, you must:
fill, font-family) or define global rules in a <style> element.This approach ensures predictable rendering by eliminating style conflicts and centralizing visual properties.
The following C# example shows how to change SVG fill safely. It finds all elements with inline styles using QuerySelectorAll, removes the fill property from their style attribute, and sets a consistent fill color using the fill presentation attribute instead.
1using Aspose.Svg.Dom;
2using System.IO;
3using System;
4using System.Collections.Generic; 1// Remove specific inline CSS properties and replace them with SVG attributes in C#
2
3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
4
5// Select elements that contain inline styles
6var nodes = document.QuerySelectorAll("[style]");
7foreach (var node in nodes)
8{
9 var element = (Element)node;
10 // Read inline style as plain text
11 var style = element.GetAttribute("style");
12 if (string.IsNullOrEmpty(style))
13 continue;
14 // Remove only fill-related declarations
15 var cleanedStyle = RemoveStyleProperty(style, "fill");
16 if (string.IsNullOrWhiteSpace(cleanedStyle))
17 {
18 // Remove empty style attribute
19 element.RemoveAttribute("style");
20 }
21 else
22 {
23 element.SetAttribute("style", cleanedStyle);
24 }
25 // Apply deterministic presentation attribute
26 element.SetAttribute("fill", "#FF7A00");
27}
28// Save the modified SVG document
29document.Save(Path.Combine(OutputDir, "style-normalized.svg"));
30
31// --- Helper method ---
32static string RemoveStyleProperty(string style, string property)
33{
34 var declarations = style.Split(';');
35 var result = new List<string>();
36 foreach (var decl in declarations)
37 {
38 if (!decl.TrimStart().StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
39 {
40 result.Add(decl.Trim());
41 }
42 }
43 return string.Join("; ", result);
44}Complete removal of inline styles is appropriate in specific scenarios, but should be used with caution.
<style> element or presentation attributes.However, complete style removal carries significant risks. Elements may revert to their default appearance with black fill and default fonts; layouts can break due to lost positioning, transforms, or opacity settings; and these changes are irreversible. Therefore, always inspect the document structure and ensure alternative styling is in place before proceeding.
Best practice: Always inspect the document structure before bulk style removal, and ensure alternative styling is in place.
style Attributes from SVG ElementsThe following C# example shows how to remove all inline style attributes in SVG document:
1using Aspose.Svg.Dom;
2using System.IO; 1// Remove all inline style attributes from SVG elements to prevent CSS conflicts in C#
2
3// Load an existing SVG document
4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
5
6// Select all elements that have inline style attributes
7var nodes = document.QuerySelectorAll("[style]");
8
9// Iterate through all styled elements
10foreach (var node in nodes)
11{
12 // Cast node to Element and remove the style attribute
13 if (node is Element element)
14 {
15 element.RemoveAttribute("style");
16 }
17}
18
19// Save the modified SVG document without inline styles
20document.Save(Path.Combine(OutputDir, "inline-styles-removed.svg"));This creates a clean baseline for CSS rules or presentation attributes.
<style> ElementThis example demonstrates a common SVG normalization workflow: removing scattered inline styles and replacing them with centralized CSS rules. This approach improves maintainability, reduces file size, and ensures consistent styling across all text elements.
1using Aspose.Svg.Dom.Svg;
2using System.IO; 1// Apply global CSS styles to SVG text after removing conflicting inline styles in C#
2
3// Load SVG document
4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg")))
5{
6 // Select all text-related elements
7 var textNodes = document.QuerySelectorAll("text, tspan");
8
9 // Remove inline style attributes
10 for (int i = 0; i < textNodes.Length; i++)
11 {
12 Element element = textNodes[i] as Element;
13 if (element != null && element.HasAttribute("style"))
14 {
15 element.RemoveAttribute("style");
16 }
17 }
18
19 // Create global <style> element
20 SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
21 style.SetAttribute("type", "text/css");
22 style.TextContent =
23 "text { " +
24 "font-family: 'DejaVu Sans', sans-serif; " +
25 "font-size: 16px; " +
26 "fill: #2c3e50; " +
27 "}";
28
29 // Insert style at the top of SVG
30 SVGSVGElement root = document.RootElement;
31 root.InsertBefore(style, root.FirstChild);
32
33 // Save result
34 document.Save(Path.Combine(OutputDir, "styled-text.svg"));
35}The example uses QuerySelectorAll to target all text-related elements, removes their inline styles, and inserts a global style rule at the beginning of the document using
InsertBefore.
Choose the appropriate strategy based on your workflow:
<style> element when enforcing consistent, centralized styling.A reliable SVG style modification pipeline in C# follows this order:
Skipping these steps often leads to style changes that execute successfully in code but do not affect the rendered SVG.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.