在特定条件后选择下一个节点

时间:2013-07-17 20:33:46

标签: java parsing xml-parsing jsoup

我正在尝试在下面的html中选择span标记之后的下一个节点值(数字4)。我怎么能这样做?

<tr valign="top">
    <td></td>
    <td><a href="#"> 1 </a></td>
    <td><a href="#"> 2 </a></td>
    <td><span> 3 </span></td>
    <td><a href="#"> 4 </a></td>
    <td><a href="#"> 5 </a></td>
    <td><a href="#"> 6 </a></td>
</tr>

1 个答案:

答案 0 :(得分:0)

final String html = "<tr valign=\"top\">\n"
        + "    <td></td>\n"
        + "    <td><a href=\"#\"> 1 </a></td>\n"
        + "    <td><a href=\"#\"> 2 </a></td>\n"
        + "    <td><span> 3 </span></td>\n"
        + "    <td><a href=\"#\"> 4 </a></td>\n"
        + "    <td><a href=\"#\"> 5 </a></td>\n"
        + "    <td><a href=\"#\"> 6 </a></td>\n"
        + "</tr>";

Document doc = Jsoup.parse(html);

Element nextToSpan = doc.select("span").first().nextElementSibling();

<强>解释

doc.select("span") // Select the span-tags of doc
    .first()    // retrieve the first one
    .nextElementSibling();  // Get the element that's next to it

文档: http://jsoup.org/cookbook/extracting-data/selector-syntax