如何将css文件解析成xml格式或者是dom对象,方便对其属性进行操作?

如何将css文件解析成xml格式或者是dom对象,方便对其属性进行操作?


炎炎设计
浏览 722回答 3
3回答

蛊毒传说

你需要使用 JavaScript 解析 styleSheets,得到 cssRules 中每个 selectorText 和对应的 cssText。下面的例子是解析后放到一个 json 对象中。123456789101112131415<style &nbsp; type="text/css">#foo {&nbsp;&nbsp;&nbsp;&nbsp;background:&nbsp;#f00;&nbsp;&nbsp;&nbsp;&nbsp;width:&nbsp;200px;&nbsp;&nbsp;&nbsp;&nbsp;height:&nbsp;200px;}.bar {&nbsp;&nbsp;&nbsp;&nbsp;float:&nbsp;left;&nbsp;&nbsp;&nbsp;&nbsp;clear:&nbsp;both;&nbsp;&nbsp;&nbsp;&nbsp;padding:&nbsp;20px;}div {&nbsp;&nbsp;&nbsp;&nbsp;border:&nbsp;10px&nbsp;solid&nbsp;#f00;}</style>&nbsp;1234567891011<script type="text/javascript">var&nbsp;rules = {};var&nbsp;ss = &nbsp; document.styleSheets;for(var&nbsp;i = 0; i < &nbsp; ss.length; i++) {&nbsp;&nbsp;&nbsp;&nbsp;for(var&nbsp;a &nbsp; = 0; a < ss[i].cssRules.length; a++) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;txt &nbsp; = ss[i].cssRules[a].cssText.match(/{(.*)}$/i),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value &nbsp; = txt[1].replace(/^\s+|\s+$/g,&nbsp;'');&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rules[ss[i].cssRules[a].selectorText] &nbsp; = value;&nbsp;&nbsp;&nbsp;&nbsp;}}</script>这样就得到一个 json 对象,console.log 输出的话会显示12345rules = {&nbsp;&nbsp;&nbsp;&nbsp;#foo: &nbsp; "width: 200px; height: 200px;",&nbsp;&nbsp;&nbsp;&nbsp;.bar:&nbsp;"float: &nbsp; left; clear: both, padding: 20px;",&nbsp;&nbsp;&nbsp;&nbsp;div:&nbsp;&nbsp;"border: &nbsp; 10px solid rgb(255, 0, 0);"};&nbsp;要改变属性值,需要对相应的 cssRule 进行操作,例如1234// 设置 div 的边框为 dotteddocument.styleSheets[0].cssRules[2].style.borderStyle &nbsp; =&nbsp;"dotted";// 设置 div 的边框颜色为 #00fdocument.styleSheets[0].cssRules[2].style.borderColor &nbsp; =&nbsp;"#00f";这种方法可行但还是建议使用写好的专门解析 CSS 的 JavaScript 库,用起来很方便。Google 一下 JSCSSP、CSS Parser、CSSOM、这些都是比较专业和成熟的 CSS 解析器。&nbsp;

莫回无

如下所示:public void transformDomToXml(Document document,String FileName){try{TransformerFactory tFactory = TransformerFactory.newInstance();Transformer transformer = tFactory.newTransformer();DOMSource source = new DOMSource(document);StreamResult result = new StreamResult(new File(FileName));transformer.transform(source,result);}catch (TransformerConfigurationException tce) {System.out.println(" " + tce.getMessage() );}catch (TransformerException te) {System.out.println(" " + te.getMessage() );}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

CSS3