Performing read and write operations on targeted CSS classes using C#

I'm currently developing a C# application that needs to manipulate CSS files. Imagine you have the following CSS code snippet:

.ClassOne
{   
    color: #FFFFFF;    
    font-weight:normal;
    font-size: 9pt;
    font-family: Tahoma;                    
    vertical-align: middle;
    border: solid 1px #7F7F7F;  
    padding: 1px 1px 1px 1px;
    background-color: #B48410;
    background-position: center center;
}

.ClassTwo
{
    color: #FFFFFF;        
        background-repeat: repeat-x;
    background-color: #000000;
}

.ClassThree
{   
    color: #000000;    
    font-weight:normal;
    font-size: 9pt;
    font-family: Tahoma;                    
    vertical-align: left;
    border: solid 1px #F3Dc51;  
    padding: 1px 1px 1px 1px;
    background-color: #A32DF1;
}

My goal is to search for specific classes in the file, such as ClassOne, and extract the corresponding background-color property for those classes. This task only needs to be done for certain classes in the CSS file - for example, I may only want to extract the background-color values for ClassOne and ClassThree.

The resulting application should then transfer these stored values to another CSS file with the same set of classes.

I am aware of ExCSS but unsure about its utility in this context and how to effectively leverage it. Can someone provide guidance on this matter?

Answer №1

To kickstart your journey with ExCss, you can begin by focusing on the parsing aspect. Here's a snippet to guide you:

    [Test]
    public void Apple([Values (".ClassThree")] string targetClass, [Values ("#A32DF1")] string expectedColor)
    {
        var parser = new Parser();
        var sheet = parser.Parse(sample);
        var result = sheet.Rulesets
            .Where(s => s.Selector.ToString() == targetClass)
            .SelectMany(r => r.Declarations)
            .FirstOrDefault(d => d.Name.Equals("background-color", StringComparison.InvariantCultureIgnoreCase))
            .Term
            .ToString();
        Assert.AreEqual(expectedColor, result);            
    }

Instead of relying on Linq, you may consider iterating through your CSS and constructing a new CSS containing values from declarations that match your target criteria. Here's an example approach:

        var targetClasses = new List<string> { ".ClassOne", ".ClassThree" };
        var targetDecls = new List<string> { "background-color" };

        var parser = new Parser();
        var sheet = parser.Parse(sample);
        foreach (var r in sheet.Rulesets)
        {
            if (targetClasses.Contains(r.Selector.ToString()))
            {
                Debug.WriteLine(r.Selector.ToString());
                Debug.WriteLine("{");
                foreach (var d in r.Declarations)
                {
                    if (targetDecls.Contains(d.Name))
                    {
                        Debug.WriteLine("\t" + d);
                    }
                }
                Debug.WriteLine("}");
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the header's height to remain unchanged when using a percentage for its size?

I'm having trouble creating a header that takes up 20% to 40% of the body. When I try using percentages, it doesn't work but it works fine with pixels. Can someone explain why percentages aren't working for this? *{ margin:0; padding: ...

Cross-browser compatibility issues with animated SVG line drawing glow effect

Attempting to create a dazzling animation utilizing SVG filters and the stroke-dasharray technique to produce a gradually drawn "glowing" line effect has posed its challenges. After extensive research, a partially functional solution was crafted: JSFiddle ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

Adjusting the height of one element based on the height of another element in multiple cases using jQuery

I am currently using jQuery to retrieve the height of one div and apply that value as a CSS property to another. Let's take a look at a sample layout: <div class="row"> <div class="column image"> <img src="image.jpg" /> < ...

"Create a new instance of a child object using a parent class

Attempting to create JSON using JSON.Net from two classes. Below is an example of the JSON: { "UserToken" : "string", "MyProject" : { "MyProjectId" : "string", "ProjectId" : "string", "ContactId" : "string", "DisplayOrder" : "int" ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

Adjusting the size of h1 when hovering over an image

Can anyone help me figure out how to increase the width of my h1 tag when hovering over the image? I've been struggling to make it work. http://jsfiddle.net/xJ4dc/ Thank you in advance for any assistance. ...

Navigating JSON data in a POST request using C# in .NET Core version 3.1

Previously, in my .Net Core 2.1 project, I had implemented a method to handle JSON data successfully as shown below: [HttpPost] [Route("sendJsonData")] public JObject saveTemplate(JObject jsonString) { string templateName = (string)jsonString.Sel ...

Overflow and contain a flex item within another flex item

I am facing a challenge where I need to prevent a flex-child of another flex-child from overflowing the parent, ensuring it does not exceed the screen height or the height of the parent (which is also a flex-child). Here's the CodePen link for refere ...

Implementing a Custom CSS Theme in JavaFX

Hey everyone, I stumbled upon this amazing JavaFX theme called Flatter on . I've been attempting to implement it for a couple of hours now, but I'm struggling with the process. Can someone provide me with a detailed guide on how to activate thi ...

The background of the ACTK Modal Popup vanishes after multiple instances of scrolling up and down

The issue I'm facing is with the AJAX Control ToolKit Modal Popup's background (the blind curtain) disappearing after scrolling up and down several times. I have attempted to resolve this by applying various CSS styles, but unfortunately, none of ...

How can I remove the outline when focusing with the mouse, but still retain it when focusing with the

Is there a way in JavaScript to detect if an element received focus from the keyboard or mouse? I only want the outline to show when it's via the keyboard, not the mouse. If this is possible, how can I override the browser's default outlining be ...

Accessing and manipulating web elements using either XPath or CSS selectors

Having trouble selecting a specific piece of information using xpath or css selector. Error messages keep appearing. Can someone help identify the issue? This snippet is from my code: output = driver.find_element_by_xpath("//td[@class_= 'sku']" ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Is it possible to turn off the shadow on just one side?

Is there a way to remove the shadow in the red area below? I have come across similar questions but unsure how to implement those solutions here. Live Demo: http://jsfiddle.net/xFa9M/ CSS:- #list li{ border: 2px solid black; border-top-width: 1px; borde ...

What is the best way to toggle a specific div element within an ng-repeat loop?

I have a list of products. When I click on a product, it should be added to the database. If I click on the same product again, it should be removed from the database. I am toggling the wishlistFlag using ng-click. This works correctly for one div element, ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

CSS navbar with a unique design: Issue with List Hover not Persisting

I'm facing a common issue with a pure CSS navbar. I have constructed a navbar using ul and li elements, but I am unable to make the menus stay visible when I hover over them. The problem lies in the fact that the menu opens only when I hover over the ...

What methods does Coinbase use to achieve this effect? Is it possible to recreate it in a React application? (Dropdown menu positioned relative to a button on hover or click

Notice the hover effect on the Businesses section, where a prepositioned dropdown menu appears, spanning the full width of the screen. How was this effect achieved and can it be recreated in React if it wasn't originally coded using React? https://i. ...