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

如何使用Jsoup拆分嵌套HTML标签为独立标签?求更优实现方案

优化Jsoup实现:拆分单个<p>标签为两个独立标签

Hey there! Let's break down your problem and refine that Jsoup code to split the single <p> tag into two separate ones more cleanly.

需求说明

需将指定HTML中的单个<p>标签拆分为两个独立的<p>标签。

原始HTML代码

<div> 
  <h2> Making Things Possible </h2> 
  <p><em><br> by David</em>, Year 2012</p> 
</div>

目标HTML格式

<div> 
  <h2> Making Things Possible </h2> 
  <p><em><br> by David</em></p> 
  <p>Year 2012</p> 
</div>

你尝试的Jsoup代码

Elements byline = elements.select("p"); 
if (!byline.isEmpty()&& elements.select("p").first().text().contains("by") ) { 
    if (byline.select("p em").first().text().contains("by")) { 
        Element firstH2heading = elements.select("h2").first(); 
        if (firstH2heading!=null) { 
            firstH2heading.after("<p><em>"+byline.select("p em").first().text()+"<em><p>"); 
        } 
        byline.select("p em").first().remove(); 
    } 
}

更优的实现方案

Your approach is on the right track, but we can simplify the logic, reduce redundant selector calls, and use Jsoup's native element APIs instead of raw HTML string concatenation (which is safer and more maintainable):

// Grab the target <p> element directly
Element pElement = elements.selectFirst("p");
if (pElement != null) {
    // Get the nested <em> element inside the <p>
    Element emElement = pElement.selectFirst("em");
    if (emElement != null && emElement.text().contains("by")) {
        // Extract the text after the <em> element, cleaning up extra commas/spaces
        String remainingText = pElement.ownText().trim();
        if (remainingText.startsWith(",")) {
            remainingText = remainingText.substring(1).trim();
        }
        
        // Create a new <p> element to hold the remaining text
        Element newPElement = new Element(Tag.valueOf("p"), "");
        newPElement.text(remainingText);
        
        // Reset the original <p> to only contain the <em> element, then add the new <p> after it
        pElement.empty().appendChild(emElement);
        pElement.after(newPElement);
    }
}

Key improvements:

  • Faster selector usage: Use selectFirst() instead of select() followed by first() to avoid creating unnecessary Elements collections
  • Safer element manipulation: Avoid raw HTML string building by using Jsoup's built-in methods like empty(), appendChild(), and new Element()
  • Cleaner text handling: Trim and clean up the remaining text to remove extra commas and spaces, ensuring the output matches your target exactly
  • Simpler logic: Streamlined conditional checks and step-by-step element operations make the code easier to read and debug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:46