c# - C#中CSS为字符串时设置CSS属性的值

标签 c# css parsing

我在 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/

相关文章:

c - 为什么我的 yacc 规则不能在这里减少?

c++ - x3 在运行时修改解析器

c# - 从两个列表中计算所有可能的项目对?

c# - 缺少 System.Windows.Shell 引用

c# - 为什么 PictureBox.Invalidate() 会导致程序崩溃? System.AccessViolationException异常

css - 如何删除具有特定类名的最后一个 div 的边框? [ :last-child] is not working

jquery - 当发生页面大小调整时,内容会滚动到 chrome 和 ie8 中的标题上

c# - .Net Core 2.1项目,为什么Nuget会还原.Net 4.6.1包?

javascript - 无法理解 element.style.color 的行为

perl - 为什么 Perl 的 Spreadsheet::ParseExcel 永远不会从 $parser->parse ('test.xls' 返回)?