Replace text in HTML within multiple tags using Jsoup in Java -


I'm reading an HTML file line by row using Java. Let's say I have an HTML line

  & lt; P & gt; Hi everyone. This is a & lt; Em> The dead end is there. & Lt; / Em> do not go! & Lt; / P & gt;  

I type the text in the row

   There is no dead end. & Lt; / Em> You can go! & Lt; / P & gt;  

will be given as input

  • Change to : Do not go it's a dead end!
  • Change to: This is not a dead end you can go! please

    As an alternative to

    MCL solution, here's a fully supported one:

    First of all, how is it that JSW sees your HTML:

      org.jsoup.nodes.TextNode: Hi everyone. This is an org.jsoup.nodes. Element: & lt; Em> Dead end & Lt; / Em> Org.jsoup.nodes.TextNode: Do not go!  

    All three nodes & lt; P & gt; ... & lt; / P & gt; element has children.

    And here (very verbose) code:

      last string html = "& lt; p> Hi everyone, this is a & lt; em & gt; Dead end. & Lt; / em> Do not go! & Lt; / p & gt; "; Document doctor = jesup.prebodiefragment (html); // Paste HTML into an HTML element pTag = doc.select ("p"). first (); // Choose P-Element (only one) // text before the 'AM' tag Textains prem = (textnode) pTag.childNode (0); Replace PreEM.text (preEM.text (). ("This is a", "this is not")); // Text after text 'em'-tag TextNode postEM = (TextNode) pTag.childNode (2); PostEM.text ("You can go!"); Println (pTag); // print result  

    Output:

      & lt; P & gt; Hi everyone. This & lt; Em> There is no dead end. & Lt; / Em> You can go! & Lt; / P & gt;  

    It contains all HTML formatting and / or will work in full documents.


Comments

Popular posts from this blog

Member with no value in F# -

java - Joda Time Interval Not returning what I expect -

c# - Showing a SelectedItem's Property -