【问题标题】:Is there a standard way to get all elements with a class name WITHIN a certain node?是否有一种标准方法可以在某个节点内获取具有类名的所有元素?
【发布时间】:2015-06-06 16:10:45
【问题描述】:

我知道Document.getElementsByClassname(String) 可以获取整个文档中特定类名的所有元素。

我现在正试图在文档的特定节点中获取这些元素。在org.w3c.dom.Element,我只找到getElementsByTagname。我真的需要遍历所有这些元素并读取类名,还是有更好的方法?

我正在尝试仅使用 Java 找到解决方案(可以使用其他库)。

非常感谢!

【问题讨论】:

  • 不,我的意思是 Java。 Java 中有一个标准的 DOM 库(org.w3c.dom.*),但它不包含我所指出的这种方法。我想知道在哪里可以找到它。

标签: java dom w3c


【解决方案1】:

尽管您正在使用 org.w3c.dom.Document 对象,但这也应该可以工作。

我在Getting specific elements with XPath from an SVG with Batik 中找到了一个使用xalan 库的解决方案。唯一的区别是我最终使用了XPathAPI 而不是XPathEvaluator,因为batikorg.w3c.dom.xpath.XPathEvaluator 实现不一致。

这是我写的代码的相关部分:

Element searchRoot= document.getRootElement();
NodeList nl = XPathAPI.selectNodeList(searchRoot, ".//*[@class=\"class_name\"]");

【讨论】:

    【解决方案2】:

    我最终使用了 JSoup,其中包含我需要的方法。

    http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#getElementsByClass%28java.lang.String%29

    【讨论】:

      【解决方案3】:

      jQuery 是更好的方法。

      这会在 id 为“nodeToSearchName”的节点中选择类为“classNameToFind”的所有节点。

      $("#nodeToSearchName").find(".classNameToFind")

      【讨论】:

      • 如果我只想使用 Java 怎么办?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2019-09-07
      • 2011-10-11
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多