У меня есть следующий html (размер для литературного контента), который передается в java-метод.
Тем не менее, я хочу передать это в строку 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, кроме регулярного выражения?
Вот как это сделать с 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>