我正在寻找通过名称获取元素的方法。我尝试使用 Element.getAttributes.getAttributeNames()
一次迭代一个元素,并迭代每个元素以查找名称,然后用我要查找的名称对其进行检查。直接抓取元素的任何替代方法或优化方法?
最佳答案
这是我用来通过标签名检索元素的方法。对于 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]);
}
关于javax.swing.text.html.HTML 文档按名称获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065622/