Jsoup如何解析包含某些属性的html元素?

时间:2014-06-09 11:28:41

标签: android jsoup

我正在解析一个html片段,并希望获得包含某些属性模式的所有元素。例如,这是html片段:

<select type=button style='display:none;' name='1st6044hpy' value='1ktx95yolw'>

<input type=hidden name='1st6044hpy' value='1ktx95yolw'>

在这里,我希望获得所有名称=&#39;&#39;和价值=&#39;&#39;属性。是否有可能获得具有某些属性的元素,例如上面给定元素中的名称和值。我已经搜索了很多关于它但没有得到任何帮助。请帮我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

像这样的丑陋的简短例子:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Iterator;

public class Attributes {

    public static void main(String[] args) {

        new Attributes().doStuff();
    }

    private void doStuff() {

        String body =
                "<form method=\"POST\" action=\"/add/bundle\">\n" +
                        "\n" +
                        "    <select data-keyname=\"fieldtype\" name='1st6044hpyAAA' value='1ktx95yolwAAA1'>\n" +
                        "        <option value=\"\">Field Type...</option>\n" +
                        "    </select>\n" +
                        "\n" +
                        "    <input type=\"checkbox\" data-keyname=\"required\" name=\"1st6044hpyBBB\" value=\"1ktx95yolwBBB1\"> Required\n" +
                        "</div>\n" +
                        "\n" +
                        "</form>";


        Document jsoutp = Jsoup.parse(body, "UTF-8");

        Element root = jsoutp.select("form").get(0);
        //selects
        Elements selects = iterateElementType(root, "select");
        //inputs
        Elements inputs = iterateElementType(root, "input");
    }

    private Elements iterateElementType(Element root, String typeField) {
        Iterator<Element> iterator;
        Elements selects = root.select(typeField);
        iterator = selects.iterator();
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            if (element.hasAttr("name"))
                System.out.println("[" + typeField + "]" + "name: " + element.attr("name"));
            if (element.hasAttr("value"))
                System.out.println("[" + typeField + "]" + "value: " + element.attr("value"));
        }
        return selects;
    }
}

忽略来自main(String[] args)的来电,请查看doStuff()方法。