简体   繁体   中英

How do I use Jsoup to insert tag before element

I need to loop though all tags of type anchor with attribute href (this is working). How do I then insert a NEW tag above before each anchor/href tag using JSoup?

EDIT: Thank you for the responses. I need to clarify: Not only do I have to add new tags before href tags, but I have to nest these tags based on certain criteria. How do i nest these tags?

You can use the Element before(String html) method. Here is an example:

String html = "<div><div>Filler 1</div><div>Filler 2</div><a href=\"page.html\"/><div>Filler 3</div></div>";
Document doc = Jsoup.parse(html);
Elements elms = doc.select("a[href]");
for (Element e : elms) {
    e.before("<div>Added Now</div>");
}
System.out.println(doc.html());

This will output:

<html>
 <head></head>
 <body>
  <div>
   <div>
    Filler 1
   </div>
   <div>
    Filler 2
   </div>
   <div>
    Added Now
   </div>
   <a href="page.html"></a>
   <div>
    Filler 3
   </div>
  </div>
 </body>
</html>

Use the below program, if you want to make any operations with respect to the node.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeVisitor;

public class InsertTagBefore {
    public static void main(String... args) {
        final String html = "<div><div>Filler 1</div><div>Filler 2</div><a href=\"page.html\"/><div>Filler 3</div></div>";
        Document document = Jsoup.parse(html);

        document.select("a").forEach(action -> { // Java 8 For Each
            action.traverse(new NodeVisitor() {
                /**
                 * method is called at the Start of the node
                 * 
                 * @param node
                 * @param depth
                 */
                @Override
                public void head(Node node, int depth) {
                    node.before("<rama>head");
                }

                /**
                 * method is called at the end of the node
                 * 
                 * @param node
                 * @param depth
                 */
                @Override
                public void tail(Node node, int depth) {
                    node.before("</rama>");
                }
            });
        });
        System.out.println(document);
    }
}

I have inserted the node rama before the anchor tag.

<html>
  <head></head>
  <body>
      <div>
          <div>Filler 1</div>
          <div>Filler 2</div>
          <rama> head </rama>
          <a href="page.html"></a>
          <div>Filler 3</div>
      </div>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM