最近做一個CMS,后臺中需要使用在線編輯器對新聞進行編輯,然后發表。我用的在線編輯器是CKEditor+CKFinder。也許是我為了讓CKEditor更本地化吧,改了很多。后來發現在CKEditor中對文字設置字體、顏色、字號大小時文字的<span>標簽會出現N個的嵌套。我們知道,當span標簽以嵌套方式出現的時候,它往往是以最后一個span標簽的style方式顯示的。也就是說外面的span標簽的style就都被屏蔽了。這個讓人有點郁悶~~.
? ? ? 一開始想的解決辦法是自己在其中查找span標簽然后進行處理,但是想不好怎么解決嵌套的問題。后來琢磨使用正則表達式,也在網上查了很多資料。結果發現正則表達式真的復雜得頭疼,而且其實也無法很好地處理嵌套標簽的問題。
? ? ? 一個偶然的機會~~(這句話聽得很耳熟),我看到有人建議使用XmlDocument來進行處理。 我恍然大悟,我心里在吶喊:我的“病”有救了(還好面對的不是電線桿~~~~)。當然,使用XmlDocument之前你需要把CKEditor中的字符串處理一下,也就是符合xml規范。這個很簡單,只要在外面加一個<div>標簽作為根節點就成了。下面就貼上代碼:


?2?????var?doc?=?new?XmlDocument();
?3?????doc.LoadXml(content);
?4?????XmlNodeList?nodes?=?doc.GetElementsByTagName("span");
?5?
?6?????string?style?=?string.Empty,?preText?=?string.Empty;
?7?????foreach?(XmlNode?node?in?nodes)
?8?????{
?9?????????if?(node.InnerText?==?preText)
10?????????{
11?????????????if?(node.Attributes?!=?null?&&
12?????????????????style.IndexOf(node.Attributes["style"].Value,?StringComparison.Ordinal)?<?0)
13?????????????????style?+=?node.Attributes["style"].Value;
14?????????}
15?????????else
16?????????{
17?????????????if?(node.Attributes?!=?null)?style?=?node.Attributes["style"].Value;
18?????????????preText?=?node.InnerText;
19?????????}
20?????????if?(node.Attributes?!=?null)
21?????????{
22?????????????node.Attributes["style"].Value?=?style;
23?????????}
24?????????else
25?????????{
26?????????????node.Attributes.Append(CreateAttribute(node,?"style",?style));
27?????????????//node.Attributes.Append()
28?????????}
29?????}
30
這其中會有判斷如果span標簽里attribute為空的情況,使用了一個私有的CreateAttribute方法進行添加,這個方法的代碼如下:


?2?????{
?3?????????try
?4?????????{
?5?????????????XmlDocument?doc?=?node.OwnerDocument;
?6?????????????if?(doc?!=?null)
?7?????????????{
?8?????????????????XmlAttribute?attr?=?doc.CreateAttribute(attributeName);
?9?????????????????attr.Value?=?value;
10?????????????????node.Attributes.SetNamedItem(attr);
11?????????????????return?attr;
12?????????????}
13?????????}
14?????????catch?(Exception?err)
15?????????{
16?????????????string?desc?=?err.Message;
17?????????}
18?????????return?null;
19
這樣,這個問題就基本解決了。為什么說只是基本解決而不是根本解決?因為嵌套span還存在,只是把外層的style都寫到最里層的style?里了。完美的做法是去掉嵌套,只保留一個span。這個因為時間原因就暫且留到日后解決吧。