Search code examples
javahtmlflying-saucer

Edit HTML Document with Java


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?


Solution

  • 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>