需要从CSS中获取类

时间:2012-03-02 06:00:22

标签: java css file-io

我是java的新手我希望在hashmap或vector中存储特定css文件的所有类名(仅名称)请帮助我,我想在hashmap中存储BODY,.title,.surveyinstruct,.parthdr

e.g

  BODY{
font-family: sans-serif;
color: #cccccc;
font-size: medium;
font-style: normal;
font-weight: bold;
background-color: black;
background-image: url(images/BLACKbody_whitemarble.jpg);
}
.title{
font-family: sans-serif;
color: Navy;
font-size: medium;
font-style: normal;
font-weight: bold;
background-color: Transparent;
border: no;
}
.surveyinstruct{
font-family: Arial;
color: black;
font-size: small;
font-style: normal;
font-weight: normal;
background-color: Transparent;
border: no;
}
.parthdr{
color: Navy;
font-size: x-small;
font-style: normal;
font-weight: bold;
background-color: #999999;
border: no;
font-family: Arial;
}

现在我必须在hashmap或vector中存储BODY,.title,.surveyinstruct,.parthdr  即hashmap应该包含我可以用于进一步工作的所有类名                 提前谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用CSS Parser。这不是完美而且那么简单,但它会给你更多......

public Map<String, CSSStyleRule> parseCSS() throws IOException {
    Map<String, CSSStyleRule> rules = new HashMap<String, CSSStyleRule>();

    InputSource inputSource = new InputSource(new FileReader("bootstrap.css"));
    CSSStyleSheet styleSheet = new CSSOMParser().parseStyleSheet(inputSource, null, null);

    CSSRuleList ruleList = styleSheet.getCssRules();
    for (int i = 0; i < ruleList.getLength(); i++) {
        CSSRule rule = ruleList.item(i);
        if (rule.getType() == CSSRule.STYLE_RULE) {
            CSSStyleRule styleRule = (CSSStyleRule) rule;
            rules.put(styleRule.getSelectorText(), styleRule);
        }
    }

    return rules;
}