如何将html片段注入包含有效html的字符串?

时间:2014-03-14 04:59:24

标签: java html xml jsoup

我有以下传递给java方法的html(文学内容的大小)。

但是,我想把这个传递给html字符串并添加一个< pre>包含一些传入的文本的标记,并添加< script type =" text / javascript">的一部分到了头。

String buildHTML(String htmlString, String textToInject)
{
  // Inject inject textToInject into pre tag and add javascript sections
  String newHTMLString = <build new html sections>
}

- htmlString -

<html>
  <head>
  </head>
  <body>
  <body>
</html>

- newHTMLString

<html>
  <head>
    <script type="text/javascript">
        window.onload=function(){alert("hello?";}
    </script>
  </head>
  <body>
     <div id="1">
        <pre>
          <!-- Inject textToInject here into a newly created pre tag-->
        </pre>
     </div>
  <body>
</html>

除了正则表达式之外,在java中执行此操作的最佳工具是什么?

1 个答案:

答案 0 :(得分:1)

以下是使用 Jsoup

执行此操作的方法
public String buildHTML(String htmlString, String textToInject)
{
    // Create a document from string
    Document doc = Jsoup.parse(htmlString);

    // create the script tag in head
    doc.head().appendElement("script")
            .attr("type", "text/javascript")
            .text("window.onload=function(){alert(\'hello?\';}");


    // Create div tag
    Element div = doc.body().appendElement("div").attr("id", "1");

    // Create pre tag
    Element pre = div.appendElement("pre");
    pre.text(textToInject);

    // Return as string
    return doc.toString();
}

我经常使用链接,意思是:

doc.body().appendElement(...).attr(...).text(...)

完全相同
Element example = doc.body().appendElement(...);
example.attr(...);
example.text(...);

示例:

final String html = "<html>\n"
        + "  <head>\n"
        + "  </head>\n"
        + "  <body>\n"
        + "  <body>\n"
        + "</html>";

String result = buildHTML(html, "This is a test.");

System.out.println(result);

<强>结果:

<html>
 <head> 
  <script type="text/javascript">window.onload=function(){alert('hello?';}</script>
 </head> 
 <body>  
  <div id="1">
   <pre>This is a test.</pre>
  </div>
 </body>
</html>