28

c# でスタイルシートから css をインライン化する必要があります。

これがどのように機能するかのように。

http://www.mailchimp.com/labs/inlinecss.php

CSS はシンプルで、クラスのみで、派手なセレクターはありません。

正規表現を使用し(?<rule>(?<selector>[^{}]+){(?<style>[^{}]+)})+てCSSからルールを削除し、クラスが呼び出される場所で単純な文字列を置き換えようと考えていましたが、一部のhtml要素にはすでにスタイルタグがあるため、それを考慮する必要があります良い。

より簡単なアプローチはありますか?または、すでに c# で書かれているものですか?

更新 - 2010 年 9 月 16 日

html も有効な xml であれば、単純な CSS インライナーを思いつくことができました。正規表現を使用して、<style />要素内のすべてのスタイルを取得します。次に、css セレクターを xpath 式に変換し、既存のインライン スタイルの前に、スタイル インラインを一致する要素に追加します。

CssToXpath は完全には実装されていないことに注意してください。まだ実行できないことがいくつかあります。

CssInliner.cs

using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.XPath;

namespace CssInliner
{
    public class CssInliner
    {
        private static Regex _matchStyles = new Regex("\\s*(?<rule>(?<selector>[^{}]+){(?<style>[^{}]+)})",
                                                RegexOptions.IgnoreCase
                                                | RegexOptions.CultureInvariant
                                                | RegexOptions.IgnorePatternWhitespace
                                                | RegexOptions.Compiled
                                            );

        public List<Match> Styles { get; private set; }
        public string InlinedXhtml { get; private set; }

        private XElement XhtmlDocument { get; set; }

        public CssInliner(string xhtml)
        {
            XhtmlDocument = ParseXhtml(xhtml);
            Styles = GetStyleMatches();

            foreach (var style in Styles)
            {
                if (!style.Success)
                    return;

                var cssSelector = style.Groups["selector"].Value.Trim();
                var xpathSelector = CssToXpath.Transform(cssSelector);
                var cssStyle = style.Groups["style"].Value.Trim();

                foreach (var element in XhtmlDocument.XPathSelectElements(xpathSelector))
                {
                    var inlineStyle = element.Attribute("style");

                    var newInlineStyle = cssStyle + ";";
                    if (inlineStyle != null && !string.IsNullOrEmpty(inlineStyle.Value))
                    {
                        newInlineStyle += inlineStyle.Value;
                    }

                    element.SetAttributeValue("style", newInlineStyle.Trim().NormalizeCharacter(';').NormalizeSpace());
                }
            }

            XhtmlDocument.Descendants("style").Remove();
            InlinedXhtml = XhtmlDocument.ToString();
        }

        private List<Match> GetStyleMatches()
        {
            var styles = new List<Match>();

            var styleElements = XhtmlDocument.Descendants("style");
            foreach (var styleElement in styleElements)
            {
                var matches = _matchStyles.Matches(styleElement.Value);

                foreach (Match match in matches)
                {
                    styles.Add(match);
                }
            }

            return styles;
        }

        private static XElement ParseXhtml(string xhtml)
        {
            return XElement.Parse(xhtml);
        }
    }
}

CssToXpath.cs

using System.Text.RegularExpressions;

namespace CssInliner
{
    public static class CssToXpath
    {
        public static string Transform(string css)
        {
            #region Translation Rules
            // References:  http://ejohn.org/blog/xpath-css-selectors/
            //              http://code.google.com/p/css2xpath/source/browse/trunk/src/css2xpath.js
            var regexReplaces = new[] {
                                          // add @ for attribs
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([^\]~\$\*\^\|\!]+)(=[^\]]+)?\]", RegexOptions.Multiline),
                                              Replace = @"[@$1$2]"
                                          },
                                          //  multiple queries
                                          new RegexReplace {
                                              Regex = new Regex(@"\s*,\s*", RegexOptions.Multiline),
                                              Replace = @"|"
                                          },
                                          // , + ~ >
                                          new RegexReplace {
                                              Regex = new Regex(@"\s*(\+|~|>)\s*", RegexOptions.Multiline),
                                              Replace = @"$1"
                                          },
                                          //* ~ + >
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*])~([a-zA-Z0-9_\-\*])", RegexOptions.Multiline),
                                              Replace = @"$1/following-sibling::$2"
                                          },
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*])\+([a-zA-Z0-9_\-\*])", RegexOptions.Multiline),
                                              Replace = @"$1/following-sibling::*[1]/self::$2"
                                          },
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*])>([a-zA-Z0-9_\-\*])", RegexOptions.Multiline),
                                              Replace = @"$1/$2"
                                          },
                                          // all unescaped stuff escaped
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([^=]+)=([^'|""][^\]]*)\]", RegexOptions.Multiline),
                                              Replace = @"[$1='$2']"
                                          },
                                          // all descendant or self to //
                                          new RegexReplace {
                                              Regex = new Regex(@"(^|[^a-zA-Z0-9_\-\*])(#|\.)([a-zA-Z0-9_\-]+)", RegexOptions.Multiline),
                                              Replace = @"$1*$2$3"
                                          },
                                          new RegexReplace {
                                              Regex = new Regex(@"([\>\+\|\~\,\s])([a-zA-Z\*]+)", RegexOptions.Multiline),
                                              Replace = @"$1//$2"
                                          },
                                          new RegexReplace {
                                              Regex = new Regex(@"\s+\/\/", RegexOptions.Multiline),
                                              Replace = @"//"
                                          },
                                          // :first-child
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*]+):first-child", RegexOptions.Multiline),
                                              Replace = @"*[1]/self::$1"
                                          },
                                          // :last-child
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*]+):last-child", RegexOptions.Multiline),
                                              Replace = @"$1[not(following-sibling::*)]"
                                          },
                                          // :only-child
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*]+):only-child", RegexOptions.Multiline),
                                              Replace = @"*[last()=1]/self::$1"
                                          },
                                          // :empty
                                          new RegexReplace {
                                              Regex = new Regex(@"([a-zA-Z0-9_\-\*]+):empty", RegexOptions.Multiline),
                                              Replace = @"$1[not(*) and not(normalize-space())]"
                                          },
                                          // |= attrib
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([a-zA-Z0-9_\-]+)\|=([^\]]+)\]", RegexOptions.Multiline),
                                              Replace = @"[@$1=$2 or starts-with(@$1,concat($2,'-'))]"
                                          },
                                          // *= attrib
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([a-zA-Z0-9_\-]+)\*=([^\]]+)\]", RegexOptions.Multiline),
                                              Replace = @"[contains(@$1,$2)]"
                                          },
                                          // ~= attrib
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([a-zA-Z0-9_\-]+)~=([^\]]+)\]", RegexOptions.Multiline),
                                              Replace = @"[contains(concat(' ',normalize-space(@$1),' '),concat(' ',$2,' '))]"
                                          },
                                          // ^= attrib
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([a-zA-Z0-9_\-]+)\^=([^\]]+)\]", RegexOptions.Multiline),
                                              Replace = @"[starts-with(@$1,$2)]"
                                          },
                                          // != attrib
                                          new RegexReplace {
                                              Regex = new Regex(@"\[([a-zA-Z0-9_\-]+)\!=([^\]]+)\]", RegexOptions.Multiline),
                                              Replace = @"[not(@$1) or @$1!=$2]"
                                          },
                                          // ids
                                          new RegexReplace {
                                              Regex = new Regex(@"#([a-zA-Z0-9_\-]+)", RegexOptions.Multiline),
                                              Replace = @"[@id='$1']"
                                          },
                                          // classes
                                          new RegexReplace {
                                              Regex = new Regex(@"\.([a-zA-Z0-9_\-]+)", RegexOptions.Multiline),
                                              Replace = @"[contains(concat(' ',normalize-space(@class),' '),' $1 ')]"
                                          },
                                          // normalize multiple filters
                                          new RegexReplace {
                                              Regex = new Regex(@"\]\[([^\]]+)", RegexOptions.Multiline),
                                              Replace = @" and ($1)"
                                          },

                                      };
            #endregion

            foreach (var regexReplace in regexReplaces)
            {
                css = regexReplace.Regex.Replace(css, regexReplace.Replace);
            }

            return "//" + css;
        }
    }

    struct RegexReplace
    {
        public Regex Regex;
        public string Replace;
    }
}

そしていくつかのテスト

    [TestMethod]
    public void TestCssToXpathRules()
    {
        var translations = new Dictionary<string, string>
                               {
                                   { "*", "//*" }, 
                                   { "p", "//p" }, 
                                   { "p > *", "//p/*" }, 
                                   { "#foo", "//*[@id='foo']" }, 
                                   { "*[title]", "//*[@title]" }, 
                                   { ".bar", "//*[contains(concat(' ',normalize-space(@class),' '),' bar ')]" }, 
                                   { "div#test .note span:first-child", "//div[@id='test']//*[contains(concat(' ',normalize-space(@class),' '),' note ')]//*[1]/self::span" }
                               };

        foreach (var translation in translations)
        {
            var expected = translation.Value;
            var result = CssInliner.CssToXpath.Transform(translation.Key);

            Assert.AreEqual(expected, result);
        }
    }

    [TestMethod]
    public void HtmlWithMultiLineClassStyleReturnsInline()
    {
        #region var html = ...
        var html = XElement.Parse(@"<html>
                                        <head>
                                            <title>Hello, World Page!</title>
                                            <style>
                                                .redClass { 
                                                    background: red; 
                                                    color: purple; 
                                                }
                                            </style>
                                        </head>
                                        <body>
                                            <div class=""redClass"">Hello, World!</div>
                                        </body>
                                    </html>").ToString();
        #endregion

        #region const string expected ...
        var expected = XElement.Parse(@"<html>
                                            <head>
                                                <title>Hello, World Page!</title>
                                            </head>
                                            <body>
                                                <div class=""redClass"" style=""background: red; color: purple;"">Hello, World!</div>
                                            </body>
                                        </html>").ToString();
        #endregion

        var result = new CssInliner.CssInliner(html);

        Assert.AreEqual(expected, result.InlinedXhtml);
    }

もっと多くのテストがありますが、それらは入力と期待される出力のために html ファイルをインポートします。

しかし、Normalize 拡張メソッドを投稿する必要があります。

private static readonly Regex NormalizeSpaceRegex = new Regex(@"\s{2,}", RegexOptions.None);
public static string NormalizeSpace(this string data)
{
    return NormalizeSpaceRegex.Replace(data, @" ");
}

public static string NormalizeCharacter(this string data, char character)
{
    var normalizeCharacterRegex = new Regex(character + "{2,}", RegexOptions.None);
    return normalizeCharacterRegex.Replace(data, character.ToString());
}
4

8 に答える 8

17

CSSをインラインにするGithubのプロジェクトがあります。非常にシンプルで、モバイル スタイルをサポートします。私のブログで詳細を読む: http://martinnormark.com/move-css-inline-premailer-net

于 2011-06-10T11:06:05.423 に答える
9

現在の実装で既に 90% の方法を達成しているため、既存のフレームワークを使用して、代わりに XML 解析を HTML パーサーに置き換えてみませんか? 最も人気のあるものの 1 つはHTML Agility Packです。XPath クエリをサポートし、XML 用に提供されている標準の .NET インターフェイスに似た LINQ インターフェイスも備えているため、かなり簡単な代替品となるはずです。

于 2010-09-21T02:50:19.503 に答える
4

すばらしい質問です。

.NETソリューションがあるかどうかはわかりませんが、CSSをインライン化すると主張するPremailerというRubyプログラムを見つけました。それを使用したい場合は、いくつかのオプションがあります。

  1. PremailerをC#(または使い慣れた.NET言語)で書き直します
  2. IronRubyを使用して.NETでRubyを実行します
于 2010-09-09T18:28:04.310 に答える
3

正規表現ではなく、実際の CSS パーサーを使用することをお勧めします。主に再生成に関心があるため、完全な言語を解析する必要はありませんが、いずれにせよ、そのようなパーサーが利用可能です (.NET の場合も同様です)。たとえば、antlr の文法のリスト、具体的にはCSS 2.1 文法またはCSS3文法を見てください。インライン スタイルに重複した定義が含まれる可能性がある最適ではない結果が気にならない場合は、両方の文法の大部分を取り除くことができますが、これをうまく行うには、省略形の属性を解決できる内部 CSS ロジックのアイデアが必要です。 .

しかし、長い目で見れば、これは終わりのない一連のアドホックな正規表現の修正よりもはるかに少ない作業になることは間違いありません。

于 2010-09-22T09:10:33.503 に答える
1

c# を使用してhttp://www.mailchimp.com/labs/inlinecss.phpにポスト コールをしない理由を考えてみましょう。firebug を使用した分析から、post 呼び出しには 2 つのパラメーターhtmlと、値 (on/off) を取るストリップが必要であるように見えます。結果は text と呼ばれるパラメーターにあります。

これは、 C# を使用してポスト コールを行う方法のサンプルです。

于 2010-09-16T07:48:44.697 に答える
1

次のような辞書をお勧めします。

private Dictionary<string, Dictionary<string, string>> cssDictionary = new Dictionary<string, Dictionary<string, string>();

css を解析して、この cssDictionary を埋めます。

(「style-type」、「style-property」、「value」を追加します。例:

Dictionary<string,string> bodyStyleDictionary = new Dictionary<string, string();
    bodyStyleDictionary.Add("background", "#000000");
    cssDictionary.Add("body", bodyStyleDictionary);

その後、できれば HTML を XmlDocument に変換します。

子によってドキュメントノードを再帰的に実行し、親を検索することもできます (これにより、セレクターを使用できるようになります)。

各要素で、要素のタイプ、ID、およびクラスを確認します。次に、cssDictionary をブラウズして、この要素のスタイルを style 属性に追加します (確かに、それらのプロパティが重複している場合は、発生順に配置することをお勧めします (そして、既存のインライン スタイルを最後に追加します)。

完了したら、xmlDocument を文字列として出力し、最初の行 ( <?xml version="1.0"?>) を削除します。これにより、インライン css を含む有効な html ドキュメントが残るはずです。

確かに、半分はハックのように見えるかもしれませんが、最終的には、安定性を確保し、探しているように見える非常に堅実なソリューションだと思います.

于 2010-09-16T14:05:27.603 に答える
1

Chad さん、CSS をインラインで追加する必要はありますか? <style>または、ブロックを追加することで、より良い結果が得られるでしょう<head>か? これは本質的に、CSS ファイルへの参照の必要性を置き換えるだけでなく、実際のインライン ルールがヘッダー/参照される css ファイルで設定されたものをオーバーライドするというルールを維持します。

(申し訳ありませんが、コードの引用符を追加するのを忘れていました)

于 2010-09-16T12:48:07.307 に答える