2013-08-05 1 views
2

이름으로 요소를 가져올 방법을 찾고 있습니다. Element.getAttributes.getAttributeNames()을 사용하여 한 번에 하나의 요소를 반복하고 각 요소를 반복하여 이름을 찾은 다음 찾고있는 이름으로 확인했습니다. 요소를 직접 잡을 수있는 대안이나 최적화 된 방법?javax.swing.text.html.HTMLDocument getElement ByName

+0

여기 참조위한 [sscce (http://sscce.org/)이야 :'DocumentParse' (http://stackoverflow.com/a/15669307/230513). – trashgod

답변

0

이름으로 요소를 가져올 방법을 찾고 있습니다.

아마도 getElement() 메서드를 사용할 수 있습니까? 검색하려는 요소의 ID에 대한 String 값을 인수로 취합니다.

+1

나는 알고 있지만이 document.getelementsbyname ('name')을 java로 찾으려고합니다 –

+0

[javax.swing.text.html] (http://docs.oracle.com/)의 설명서를 읽었습니까? javase/6/docs/api/javax/swing/text/html/HTMLDocument.html)? 그것은'document.getElement (name)'메소드를 가지고있다. document.getelementsbyname ('name')과 동일한 것이어야합니다. – scottyseus

+1

작은 오보가 있다고 생각합니다. getElement (id) 주어진 id 속성을 가진 요소를 반환합니다. 이름 속성으로 요소를 가져 오려고합니다. –

1

태그 이름으로 요소를 검색하는 방법입니다. mixed-content 요소 (예 : sub, sup, b, i)의 경우 "가짜"content 요소의 속성을 조사해야합니다.

/** 
* Returns all elements of a particular tag name. 
* 
* @param tagName The tag name of the elements to return (e.g., HTML.Tag.DIV). 
* @param document The HTML document to find tags in. 
* @return The set of all elements in the HTML document having the specified tag name. 
*/ 
public static Element[] getElementsByTagName(HTML.Tag tagName, HTMLDocument document) 
{ 
    List<Element> elements = new ArrayList<Element>(); 

    for (ElementIterator iterator = new ElementIterator(document); iterator.next() != null;) 
    { 
     Element currentEl = iterator.current(); 

     AttributeSet attributes = currentEl.getAttributes(); 

     HTML.Tag currentTagName = (HTML.Tag) attributes.getAttribute(StyleConstants.NameAttribute); 

     if (currentTagName == tagName) 
     { 
      elements.add(iterator.current()); 
     } else if (currentTagName == HTML.Tag.CONTENT) { 
      for (Enumeration<?> e = attributes.getAttributeNames(); e.hasMoreElements();) 
      { 
       if (tagName == e.nextElement()) 
       { 
        elements.add(iterator.current()); 
        break; 
       } 
      } 
     } 
    } 

    return elements.toArray(new Element[0]); 
} 
+0

여기에 관련된 예입니다 [here] (http://stackoverflow.com/a/37620890/230513). – trashgod

관련 문제