【问题标题】:Format html tag to a string java将html标签格式化为字符串java
【发布时间】:2017-06-21 03:23:03
【问题描述】:

我需要帮助 我有一个这样的字符串

String myString = "The accuracy of a potentiometer (pH meter) is
                   &#177;0.1 mV. A solution contains 1x10<SUP>-4<\/SUP> mol\/L Cl
                   <SUP>-<\/SUP> and 1x10<SUP>-3<\/SUP> mol\/L Ca<SUP>2+<\/SUP>. 
                   What is the error in concentration to be expected when measuring
                   these ions with a chloride or a calcium ion selective electrode? 
                   <TABLE BORDER=0 ALIGN=CENTER> <TR><TD>    <\/TD><TD>&nbsp;<\/TD><TD>
                   <\/TD><\/TR><\/TABLE>";

我必须在 listView 中显示这个字符串,但很明显,当我打印它时,会有这些 html 标签。

我已经尝试删除这些标签,但如果是这样,我会丢失信息(例如 -4 作为 superscipt)。 我想知道是否可以以正确的方式格式化字符串。

谢谢

更新:

我已经通过使用 Html.fromHtml(String) 部分解决了

public String processString(String html) {
    Spanned spanned;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        spanned = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        spanned = Html.fromHtml(html);
    }
    return spanned.toString();
}

现在的问题是标签显示为 obj 图标 而且我不知道如何将它们可视化。

有可能吗?

【问题讨论】:

标签: java html string listview string-formatting


【解决方案1】:

如果你修复了 html,它将被许多 Swing 组件很好地呈现,无需帮助:

import javax.swing.*;
import java.awt.*;

public class Se0124 extends JFrame
{
    String myString = "<html>" +
                   "The accuracy of a potentiometer (pH meter) is" +
                   "&#177;0.1 mV. A solution contains 1x10<SUP>-4</SUP> mol/L Cl" +
                   "<SUP>-</SUP> and 1x10<SUP>-3</SUP> mol/L Ca<SUP>2+</SUP>." +
                   "What is the error in concentration to be expected when measuring" +
                   "these ions with a chloride or a calcium ion selective electrode?" +
                   "</html>";

    public Se0124 ()
    {
        super ("Se0124");
        JPanel mainpanel = new JPanel ();
        mainpanel.setLayout (new BorderLayout ());
        this.getContentPane ().add (mainpanel);

        JLabel jl = new JLabel (myString);
        mainpanel.add (jl, BorderLayout.CENTER);
        setSize (400, 400);
        setLocation (100, 100);
        setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setVisible (true);
    }

    public static void main (String args[])
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Se0124 ();
            }
        });
    }
}

如您所见,我删除了看起来为空的尾部。然后我将它封装在标签中。我从斜杠中删除了反斜杠。

这可以通过正则表达式来完成。现在 SUP 和 SUB 可以正常渲染了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多