Set CSS property value when CSS is a string in C #
I have a string in C # which is essentially a CSS file. I can parse this CSS file and extract the values using this library, which was extremely helpful: https://github.com/TylerBrinks/ExCSS
It's all fantastic. However, now I need to change the values in the file and I cannot figure out how sure I am about this.
In simplest terms, I have this line in C #:
body
{
background-color:#323432;
}
I need to write a function:
public string ChangeValue(string oldstring, string name, string type, string value)
What's when called with this:
string newstring = ChangeValue("body{background-color:#323432;}", "body","background-color","#ffffff");
The "newstring" line above turns into this:
body
{
background-color:#ffffff;
}
In fact, I really appreciate the help. Thank.
source to share
You can accomplish this without going through the old one string
. You will need to refund string
instead 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 provided by ExCSS?
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;
}
source to share