2014-03-14 26 views
0

我有以下html(文檔內容的大小)傳遞給java方法。如何將html片段注入到包含有效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中做到這一點的最好的工具?

+0

HTML或XHTML?如果後者可以用標準的XML庫來完成。 – nablex

+0

@nablex:html但我認爲一些其他類型的XML解析會工作?可能也是jsoup? – JaJ

回答

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> 
+0

這太棒了!我會給它一個鏡頭。謝謝! – JaJ

相關問題