zed
zed

Reputation: 2338

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!

Upvotes: 1

Views: 858

Answers (2)

Andrew Henry
Andrew Henry

Reputation: 1

As of 2024–though probably much earlier—ToString() does not work. The correct selection is the ExCSS.FormatExtensions.ToCss() extension method:

using ExCSS;
.
.
.
return stylesheet.ToCss();

or

return ExCss.FormatExtensions.ToCss(stylesheet);

Upvotes: 0

zed
zed

Reputation: 2338

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.

Upvotes: 2

Related Questions