【发布时间】:2015-08-14 02:54:07
【问题描述】:
我正在寻找按名称获取元素的方法。我尝试使用Element.getAttributes.getAttributeNames() 一次迭代一个元素并遍历每个元素以找到名称,然后使用我要查找的名称检查它。直接抓取元素的任何替代或优化方式?
【问题讨论】:
-
这是一个sscce 供参考:
DocumentParse。
标签: java html swing parsing dom
我正在寻找按名称获取元素的方法。我尝试使用Element.getAttributes.getAttributeNames() 一次迭代一个元素并遍历每个元素以找到名称,然后使用我要查找的名称检查它。直接抓取元素的任何替代或优化方式?
【问题讨论】:
DocumentParse。
标签: java html swing parsing dom
这是我用来按标签名称检索元素的方法。对于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]);
}
【讨论】:
我正在寻找按名称获取元素的方法。
也许您可以使用getElement() 方法?它将您正在搜索的元素的 id 的字符串值作为参数。
【讨论】:
document.getElement(name) 方法。它应该和 document.getelementsbyname('name') 一样。