【问题标题】:javax.swing.text.html.HTMLDocument getElement ByNamejavax.swing.text.html.HTMLDocument getElement ByName
【发布时间】:2015-08-14 02:54:07
【问题描述】:

我正在寻找按名称获取元素的方法。我尝试使用Element.getAttributes.getAttributeNames() 一次迭代一个元素并遍历每个元素以找到名称,然后使用我要查找的名称检查它。直接抓取元素的任何替代或优化方式?

【问题讨论】:

标签: java html swing parsing dom


【解决方案1】:

这是我用来按标签名称检索元素的方法。对于mixed-content 元素(例如,subsupbi),您需要查看“假”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]);
}

【讨论】:

    【解决方案2】:

    我正在寻找按名称获取元素的方法。

    也许您可以使用getElement() 方法?它将您正在搜索的元素的 id 的字符串值作为参数。

    【讨论】:

    • 我知道这一点,但我希望在 java 中做这个 document.getelementsbyname('name')
    • 您是否阅读了javax.swing.text.html 的文档?它有document.getElement(name) 方法。它应该和 document.getelementsbyname('name') 一样。
    • 我认为有一个小误会,getElement(id) 返回具有给定 id 属性的元素。我正在寻找按名称属性获取元素
    • 哦,哎呀。我不知道该怎么做......只是忽略我的回答哈哈
    猜你喜欢
    • 1970-01-01
    • 2012-05-21
    • 2016-02-15
    • 2012-04-19
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多