Edit HTML Document with Java

北城余情 提交于 2019-12-06 12:44:31
rolfl

XHTML is XML, so any XML parser would be my recommendataion. I maintain the JDOM library, so would naturally recommend using that, but other libraries, including the embedded DOM model in Java will work. I would use something like:

    Document doc = new SAXBuilder().build(Main.class.getResource("/mailtemplate/DefaultMail.html"));

    // XPath that finds the `p` element with id="first"
    XPathExpression<Element> xpe = XPathFactory.instance().compile(
            "//p[@id='first']", Filters.element());
    Element p = xpe.evaluateFirst(doc);

    p.setText("This is my text");

    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(doc, System.out);

Produces the following:

<?xml version="1.0" encoding="UTF-8"?>
<html>
  <head />
  <body>
    <p id="first">This is my text</p>
    <p id="second" />
  </body>
</html>

use a fine graded Html parser and manipulation library like jsoup. You can easily create a Document by passing the html to jsoup.parse(String htmlContent) function. This library allows all of the DOM manupulation function including CSS or jquery-like selector syntax. doc.selct(String selector), where doc is an instance of Document.

For example you can select the first p using doc.select("p").first(). A minimal working solution would be:

Document doc = jsoup.parse(htmlContent);
Element p = doc.select("p").first();
p.text("My Example Text");

Reference:

  1. Use selector-syntax to find elements
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!