java swing获取div html的属性样式

时间:2015-11-14 15:35:16

标签: java html swing

我想获取url img“assets / img / slider1.jpg”。 file index.hrml:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div class="carousel-content" style="background-image:url(assets/img/slider1.jpg)"></div>                                           
    </body>
</html>

我使用它下面的代码为null。 结果Img:null。

请帮帮我。

public class getStyleHTML {

    public static void main(String[] args) throws BadLocationException, IOException {
        // TODO Auto-generated method stub
        try {
            URL url = new URL("http://localhost/test/test/index.html");
            HTMLEditorKit kit = new HTMLEditorKit(); 
            HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument(); 
            Reader HTMLReader = new InputStreamReader(url.openConnection().getInputStream());
            kit.read(HTMLReader, doc, 0);
            ElementIterator it = new ElementIterator(doc);
            Element elem = null;
            while ( (elem = it.next()) != null ){ 
                if( elem.getName().equals("div")){ 
                   String div = (String) elem.getAttributes().getAttribute(HTML.Attribute.STYLE);
                   System.out.println("Img: "+div);
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用 var result = xdoc.Root.Elements("data") .Select(x => { var ContactRow = x.Elements("data") .FirstOrDefault(z => (string)z.Attribute("name") == "CONTACT"); var PHONE1Row = x.Elements("data") .FirstOrDefault(z => (string)z.Attribute("name") == "PHONE1"); return new { Contact = (string)ContactRow, Phone1 = (string)PHONE1Row }; }); 命令获取css。然后,您可以删除background-image语法,如下所示:

url

var string =$("div").css("background-image"); string = string.replace('url(','').replace(')',''); 包含网址内容。查看工作示例here。顺便说一下,你需要使用jQuery。