0

私は (まだ) JavaHTMLEditorKitと Java に問題がありHTMLDocumentます。要素の内部 HTML しか設定できませんが、取得できません。要素の uderlying HTML コードを取得する方法はありますか?

私の問題は、HTML サポートが非常に貧弱で、書き方が悪いことです。API では、基本機能と期待される機能は許可されていません。colspanのまたは 行スパンattributeを変更する必要があり<td>ます。Java 開発者は単純な方法を閉じました: 要素の属性セットは不変です。回避策として、要素のコード (例: <td colspan="2">Hi <u>world</u></td>) を新しいコンテンツ (例: ) に置き換えることができます<td colspan="3">Hi <u>world</u></td>。この道も閉鎖されているようです。(おまけの質問: 何の役に立つのHTMLEditorKit?)

4

2 に答える 2

2

選択した Element html を取得できます。要素のオフセットを渡すキットの write() メソッドを使用します。ただし、周囲のタグ「<html>」「<body>」などに含まれます。

于 2011-10-03T14:00:11.983 に答える
0

ヒントをありがとう、スタニスラフ。それが私の解決策です:

/**
 * The method gets inner HTML of given element. If the element is named <code>p-implied</code>
 * or <code>content</code>, it returns null.
 * @param e element
 * @param d document containing given element
 * @return the inner HTML of a HTML tag or null, if e is not a valid HTML tag
 * @throws IOException
 * @throws BadLocationException
 */
public String getInnerHtmlOfTag(Element e, Document d) throws IOException, BadLocationException {
    if (e.getName().equals("p-implied") || e.getName().equals("content"))
        return null;

    CharArrayWriter caw = new CharArrayWriter();
    int i;
    final String startTag = "<" + e.getName();
    final String endTag = "</" + e.getName() + ">";
    final int startTagLength = startTag.length();
    final int endTagLength = endTag.length();

    write(caw, d, e.getStartOffset(), e.getEndOffset() - e.getStartOffset());
    //we have the element but wrapped as full standalone HTML code beginning with HTML start tag
    //thus we need unpack our element
    StringBuffer str = new StringBuffer(caw.toString());
    while (str.length() >= startTagLength) {
        if (str.charAt(0) != '<')
            str.deleteCharAt(0);
        else if (!str.substring(0, startTagLength).equals(startTag))
            str.delete(0, startTagLength);
        else
            break;
    }
    //we've found the beginning of the tag
    for (i = 0; i < str.length(); i++) { //skip it...
        if (str.charAt(i) == '>')
            break; //we've found end position of our start tag
    }
    str.delete(0, i + 1); //...and eat it
    //skip the content
    for (i = 0; i < str.length(); i++) {
        if (str.charAt(i) == '<' && i + endTagLength < str.length() && str.substring(i, i + endTagLength).equals(endTag))
            break; //we've found the end position of inner HTML of our tag
    }
    str.delete(i, str.length()); //now just remove all from i position to the end

    return str.toString().trim();
}

このメソッドを簡単に変更して、外側の HTML (つまり、タグ全体を含むコード) を取得できます。

于 2011-10-04T12:50:58.907 に答える