使用Java编辑HTML文档 [英] Edit HTML Document with Java

查看:117
本文介绍了使用Java编辑HTML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的java应用程序中存储了一个存储在内存中的HTML文档(在Flying Saucer XHTMLPanel上设置)。

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文件;

html file below;

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

我想设置 p 元素。我不想为它设置一个架构来使用getDocumentById(),那么我有什么替代方案?

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?

推荐答案

XHTML是XML,所以任何XML解析器都是我的推荐。我维护 JDOM库,因此自然会建议使用它,但其他库,包括Java中的嵌入式DOM模型将工作。我会使用类似的东西:

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);

产生以下内容:

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

这篇关于使用Java编辑HTML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆