3

I have a string in C# that's essentially a CSS file. I can parse this CSS file and extract values with this library that has been extremely helpful: https://github.com/TylerBrinks/ExCSS

That's all fantastic. However, I now need to change the values within the file and I cannot figure out for the life of me how to reliably do this.

In the simplest terms possible, I have this string in C#:

body
{
   background-color:#323432;
}

I need to write a function:

public string ChangeValue(string oldstring, string name, string type, string value)

That when called with this:

string newstring = ChangeValue("body{background-color:#323432;}", "body","background-color","#ffffff"); 

The "newstring" string above, turns into this:

body
{
   background-color:#ffffff;
}

Really really appreciate the help. Thank you.

2
  • Do you mean public string ChangeValue or are you stuck with a void return type? Commented Apr 30, 2015 at 6:38
  • You need algorithm how to parse css string? Do array from this using '}', than '{', than subarray using ';'. Or I does not understand your question? Commented Apr 30, 2015 at 6:41

1 Answer 1

4

You can accomplish this without passing in the old string. You'll need to return a string, not void.

public static string ChangeValue(string name, string type, string value) {
     return String.Format("{0}\r\n{{\r\n    {1}:{2};\r\n}}", name, type, value);
}

output:

body
{
    background-color:#ffffff;
}

But why not use the API the ExCSS exposes?

var parser = new Parser();
var stylesheet = parser.Parse(css);

var bodyBackgroundColor = stylesheet.StyleRules
  .FirstOrDefault(s => s.Selector.ToString() == "body")
  .Declarations
  .FirstOrDefault(d => d.Name == "background-color")
  .Term = new HtmlColor(255, 255, 255);

Console.WriteLine(stylesheet.ToString(true, 0));

Output:

body{
        background-color:#FFF;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just for my own knowledge, how did you figure out that the API exposes that ability?
I guessed when I saw this exposed in the public API github.com/TylerBrinks/ExCSS/blob/master/ExCSS/IToString.cs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.