2011-10-03 17 views
0

我在Java中仍然有HTMLEditorKitHTMLDocument的問題。我只能設置元素的內部HTML,但我無法得到它。有沒有辦法,如何獲得元素的uderlying HTML代碼?JEditorPane和HTML元素的來源

我的問題是,HTML支持是相當差,寫得不好。該API不支持基本功能和預期功能。我需要更改colspan或行attribute<td>。 Java開發人員已經關閉了直接的方式:元素的屬性集是不可變的。解決方法可以是將元素的代碼(例如<td colspan="2">Hi <u>world</u></td>)替換爲新的內容(例如<td colspan="3">Hi <u>world</u></td>)。這種方式似乎也被關閉了。 (紅利問題:HTMLEditorKit有什麼好處?)

回答

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

這種方法可以easilly修改,以獲得outter HTML(所以包含整個標籤的代碼)。

2

您可以得到選定的Element html。使用套件的write()方法傳遞Element的偏移量。但它會包含在周圍的標籤中「<html>」「<body>」等

+0

啊......你說得對。該實施經過優化,絕對是防彈的。與自定義此Swing HTML相比,將運動轉換爲Percolator更容易。 (但官方文檔說,_one可以輕鬆定製如何顯示特定元素或添加新元素的能力_)爲什麼實現缺乏這些基本和可預期的功能,如獲取某些元素的內部HTML? –