如何在Java中将JTextPanes/JEditorPanes html内容清理为字符串?

Mik*_*nen 2 html java string jtextpane

我试图从JTextPane获得漂亮(清理)的文本内容.以下是来自的示例代码JTextPane:

JTextPane textPane = new JTextPane ();
textPane.setContentType ("text/html");
textPane.setText ("This <b>is</b> a <b>test</b>.");
String text = textPane.getText ();
System.out.println (text);
Run Code Online (Sandbox Code Playgroud)

文字看起来像这样JTexPane:

一个考验.

我得到这种打印到控制台:

<html>
  <head>

  </head>
  <body>
    This <b>is</b> a <b>test</b>.
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我使用过substring()和/或replace()编码,但使用起来很不舒服:

String text = textPane.getText ().replace ("<html> ... <body>\n    , "");
Run Code Online (Sandbox Code Playgroud)

是否有任何简单的函数<b>从字符串中删除除标签(内容)之外的所有其他标签?

有时在内容周围JTextPane添加<p>标签,所以我也想摆脱它们.

像这样:

<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">
      hdfhdfgh
    </p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我想只获得带有标签的文字内容:

This <b>is</b> a <b>test</b>.
Run Code Online (Sandbox Code Playgroud)

les*_*ana 5

我进行了子类化HTMLWriter和覆盖,startTagendTag跳过了所有标签<body>.

我没有测试太多,似乎工作正常.一个缺点是输出字符串有很多空白.摆脱它应该不会太难.

import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class Foo {

    public static void main(String[] args) throws Exception {
        JTextPane textPane = new JTextPane();
        textPane.setContentType("text/html");
        textPane.setText("<p>This</p> <b>is</b> a <b>test</b>.");

        StringWriter writer = new StringWriter();
        HTMLDocument doc = (HTMLDocument) textPane.getStyledDocument();

        HTMLWriter htmlWriter = new OnlyBodyHTMLWriter(writer, doc);
        htmlWriter.write();

        System.out.println(writer.toString());
    }

    private static class OnlyBodyHTMLWriter extends HTMLWriter {

        public OnlyBodyHTMLWriter(Writer w, HTMLDocument doc) {
            super(w, doc);
        }

        private boolean inBody = false;

        private boolean isBody(Element elem) {
            // copied from HTMLWriter.startTag()
            AttributeSet attr = elem.getAttributes();
            Object nameAttribute = attr
                    .getAttribute(StyleConstants.NameAttribute);
            HTML.Tag name = null;
            if (nameAttribute instanceof HTML.Tag) {
                name = (HTML.Tag) nameAttribute;
            }
            return name == HTML.Tag.BODY;
        }

        @Override
        protected void startTag(Element elem) throws IOException,
                BadLocationException {
            if (inBody) {
                super.startTag(elem);
            }
            if (isBody(elem)) {
                inBody = true;
            }
        }

        @Override
        protected void endTag(Element elem) throws IOException {
            if (isBody(elem)) {
                inBody = false;
            }
            if (inBody) {
                super.endTag(elem);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)