Edit HTML Document with Java

泄露秘密 提交于 2019-12-10 11:25:10

问题


I have an HTML document stored in memory (set on a Flying Saucer XHTMLPanel) in my java application.

xhtmlPanel.setDocument(Main.class.getResource("/mailtemplate/DefaultMail.html").toString());

html file below;

<html>
    <head>
    </head>
    <body>
        <p id="first"></p>
        <p id="second"></p>
    </body>
</html>

I want to set the contents of the p elements. I don't want to set a schema for it to use getDocumentById(), so what alternatives do I have?


回答1:


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>



回答2:


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


来源:https://stackoverflow.com/questions/19730996/edit-html-document-with-java

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