我有以下传递给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中执行此操作的最佳工具是什么?
答案 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>