5

有人帮我用 jsoup 检索此示例中 text-align 样式的值吗?

<th style="text-align:right">4389</th>

在这里我想获得正确的价值

谢谢!

4

3 回答 3

7

您可以检索style元素的属性,然后将其拆分为:.

例子:

final String html = "<th style=\"text-align:right\">4389</th>";

Document doc = Jsoup.parse(html, "", Parser.xmlParser()); // Using the default html parser may remove the style attribute
Element th = doc.select("th[style]").first();


String style = th.attr("style"); // You can put those two lines into one
String styleValue = style.split(":")[1]; // TODO: Insert a check if a value is set

// Output the results
System.out.println(th);
System.out.println(style);
System.out.println(styleValue);

输出:

<th style="text-align:right">4389</th>
text-align:right
right
于 2013-06-14T15:29:29.593 回答
0
public static Map<String, String[]> getStyleMap(String styleStr) {
    Map<String, String[]> keymaps = new HashMap<>();
    // margin-top:-80px !important;color:#fcc;border-bottom:1px solid #ccc; background-color: #333; text-align:center
    String[] list = styleStr.split(":|;");
    for (int i = 0; i < list.length; i+=2) {
        keymaps.put(list[i].trim(),list[i+1].trim().split(" "));
    }
    return keymaps;
}

结果:

0 = {HashMap$Node@5713} "background-color" -> ["#333"]
1 = {HashMap$Node@5714} "color" -> ["#fcc"]
2 = {HashMap$Node@5716} "margin-top" -> ["-80px","!important"]
3 = {HashMap$Node@5717} "text-align" -> ["center"]
于 2020-04-25T13:01:33.733 回答
0

另一种提取样式属性的方法是:

public Map<String, String> getStyleMap(Element element) {
    Map<String, String> keymaps = new HashMap<>();
    if (!element.hasAttr("style")) {
        return keymaps;
    }
    String styleStr = element.attr("style"); // => margin-top:-80px !important;color:#fcc;border-bottom:1px solid #ccc; background-color: #333; text-align:center
    String[] keys = styleStr.split(":");
    String[] split;
    if (keys.length > 1) {
        for (int i = 0; i < keys.length; i++) {
            if (i % 2 != 0) {
                split = keys[i].split(";");
                if (split.length == 1) break;
                keymaps.put(split[1].trim(), keys[i + 1].split(";")[0].trim());
            } else {
                split = keys[i].split(";");
                if (i + 1 == keys.length) break;
                keymaps.put(keys[i].split(";")[split.length - 1].trim(), keys[i + 1].split(";")[0].trim());
            }
        }
    }
    return keymaps;
}

将 HashMap 填充为:

0 = {HashMap$Node@5713} "background-color" -> "#333"
1 = {HashMap$Node@5714} "color" -> "#fcc"
2 = {HashMap$Node@5715} "font-family" -> "'Helvetica Neue', Helvetica, Arial, sans-serif"
3 = {HashMap$Node@5716} "margin-top" -> "-80px !important"
4 = {HashMap$Node@5717} "text-align" -> "center"
于 2018-08-31T04:57:32.077 回答