我正在寻找按名称获取元素的方法。我尝试一次迭代一个元素,方法是使用Element.getAttributes.getAttributeNames()
并遍历每个元素以查找名称,然后使用我要查找的名称对其进行检查。直接获取元素的任何替代方法或优化方法?
问问题
1274 次
2 回答
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]);
}
于 2015-08-13T01:52:47.690 回答
0
我正在寻找按名称获取元素的方法。
也许您可以使用该getElement()
方法?它将您正在搜索的元素的 id 的字符串值作为参数。
于 2013-08-05T22:16:46.353 回答