Search code examples
c#asp.netparsinghtml-parsingcss-parsing

How to get StyleRules as a string output using ExCSS Parser


I'm using ExCSS to parse and manipulate a stylesheet string. So far so good.

But I can't find any documentation on how to convert the manipulated style rules into a string.

Although the code may not be relevant to this question, this is what I'm doing:

private string ManipulateCSS(string styles)
{
    ExCSS.Parser parser = new ExCSS.Parser();
    var stylesheet = parser.Parse(styles);

    // here I perform specific manipulations 
    // which are not relevant to this question...
    stylesheet.StyleRules
                  .SelectMany(r => r.Declarations)
                  .Where(d => d.Name == "<something>"
                  ...

    ...

    // Now, the next line is where I'm having issues: 
    // how to return the whole string with styles out of this ExCSS parser?
    return stylesheet.StyleRules.ToString();
}

Thank you for your help!


Solution

  • Turns out the ToString() method needs to be called on the ExCSS.StyleSheet instance and I was calling it on the StyleRules collection.

    You only need to do the following (as per my sample code in the question above):

    return stylesheet.ToString();
    

    I hope this answer might save someone else's time.