我在 C# 中有一个字符串,它本质上是一个 CSS 文件。我可以解析这个 CSS 文件并使用这个非常有用的库提取值:https://github.com/TylerBrinks/ExCSS
这一切都太棒了。但是,我现在需要更改文件中的值,但我终究无法弄清楚如何可靠地执行此操作。
用最简单的术语来说,我在 C# 中有这个字符串:
body
{
background-color:#323432;
}
我需要写一个函数:
public string ChangeValue(string oldstring, string name, string type, string value)
用这个调用时:
string newstring = ChangeValue("body{background-color:#323432;}", "body","background-color","#ffffff");
上面的“newstring”字符串,变成这样:
body
{
background-color:#ffffff;
}
非常感谢您的帮助。谢谢。
最佳答案
您可以在不传递旧的 string
的情况下完成此操作。您需要返回一个 string
,而不是 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);
}
输出:
body
{
background-color:#ffffff;
}
但为什么不使用 ExCSS 公开的 API 呢?
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));
输出:
body{
background-color:#FFF;
}
关于c# - C#中CSS为字符串时设置CSS属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29960597/