以下 wffweb java 代码(与 wffweb 网站上提供的示例相对接近):
html = new Html(null) {{
new Head(this) {{
new TitleTag(this) {{
new NoTag(this, "No <tags> inside, please!");
}};
}};
}};
System.out.println(html.toHtmlString());
打印输出:
<html><head><title>No <tags> inside, please!</title></head></html>
我期望(和需要)的是使用相应的机制对文本节点内的任何 XML 字符进行转义(在本例中 <tags>
应该是 <tags>
)。
在输出中转义文本节点内的 XML 语法的正确(或推荐)方法是什么?显然,我自己可以在添加字符串之前包装 XML 语法,但这听起来不对,我不必每次都转义/取消转义文本节点值,我希望它们作为常规字符串存储在树中,并且仅在序列化期间修改。
最佳答案
您可以创建由 NoTag
扩展的自定义类。您还必须使用 org.apache.commons.text.StringEscapeUtils.escapeHtml4 方法将特殊字符转换为其中的 xml 实体。这是推荐的方式,因为我们正在扩展 NoTag
的功能。
例如:
public class EscapeXmlNoTag extends NoTag {
private final String content;
public EscapeXmlNoTag(AbstractHtml base, String content) {
super(base, org.apache.commons.text.StringEscapeUtils.escapeHtml4(content), true);
this.content = content;
}
public String getContent() {
return content;
}
}
您可以使用此 EscapeXmlNoTag
类代替 NoTag
,如下所示
Html rootTag = new Html(null).give(html -> {
new Head(html).give(head -> {
new TitleTag(head).give(title -> {
new EscapeXmlNoTag(title, "No <tags> inside, please!");
});
});
});
System.out.println(rootTag.toHtmlString());
打印
<html><head><title>No <tags> inside, please!</title></head></html>
<小时/>
如果处理得当,后期绑定(bind)也是可能的。如果文本内容转换繁重,想要进行并行操作那么比较合适。最新版本的wffweb是线程安全的。例如:
List<Runnable> tasks = new ArrayList<>();
Html rootTag = new Html(null).give(html -> {
new Head(html).give(head -> {
new TitleTag(head).give(title -> tasks.add(() -> new EscapeXmlNoTag(title, "No <tags> inside, please!")));
new Body(head).give(body -> {
new Div(body).give(div -> tasks.add(() -> new EscapeXmlNoTag(div, "<div> content goes here")));
});
});
});
tasks.parallelStream().forEach(Runnable::run);
tasks.clear();
System.out.println(rootTag.toHtmlString());
打印
<html><head><title>No <tags> inside, please!</title><body><div><div> content goes here</div></body></head></html>
在此示例中,TitleTag
和 Div
只有一个子级(即只有 NoTag
),因此不存在执行顺序问题否则需要维护任务
的执行顺序。
关于java - 如何在 wffweb 中正确渲染 HTML 树中的任意文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58628727/