You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jsoup仅保留目录中的Level1与Level2层级元素?

Fixing Multi-Level TOC to Keep Only Level 1 and 2 Elements with Jsoup

It sounds like your parent-count approach hit a snag—probably because the DOM structure has extra wrapping elements that throw off the parent count logic. Let's switch to a more direct, reliable method by explicitly targeting the levels you want to keep.

Here's a revised approach that preserves only Level 1 and Level 2 items, stripping out all deeper nesting:

File in = new File(INPUT_FILE_PATH);
Document origDoc = Jsoup.parse(in, null);

// Grab the main TOC container
Element toc = origDoc.selectFirst(".toc");
if (toc == null) {
    System.err.println("Couldn't find the TOC container!");
    return;
}

// Get the root-level UL (this holds all Level 1 items)
Element level1Root = toc.selectFirst("ul");
if (level1Root == null) {
    System.err.println("No top-level UL found in TOC!");
    return;
}

// Loop through each Level 1 list item
for (Element level1Item : level1Root.children()) {
    // Find all ULs inside this Level 1 item
    Elements nestedUls = level1Item.select("ul");
    
    if (!nestedUls.isEmpty()) {
        // Keep only the first UL (this is your Level 2)
        Element level2Ul = nestedUls.first();
        // Remove any ULs inside the Level 2 UL (these are Level 3+ items)
        level2Ul.select("ul").remove();
    }
    // Optional: If your Level 1 items have other content besides the Level 2 UL,
    // you can leave it as is or clean it up here depending on your needs
}

// Save the modified document to file
try (FileWriter out = new FileWriter(new File(OUTPUT_FILE_PATH))) {
    out.write(origDoc.outerHtml());
} catch (IOException e) {
    e.printStackTrace();
}

Key Details:

  • We start by targeting the .toc container and its top-level ul (Level 1 root).
  • For each Level 1 list item, we keep its direct child ul (Level 2) and delete any nested ul elements inside that Level 2 list (which are Level 3 and deeper).
  • This method avoids relying on parent counts, which can be unreliable if your TOC has extra divs or spans wrapping elements.

If your TOC structure is slightly different (e.g., multiple top-level ul elements), you can adjust the selector to toc.select("> ul") to grab only direct child uls of the TOC container instead of the first ul found.

内容的提问来源于stack exchange,提问作者Claude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:53