是否有一种标准方法来获取某个节点内具有 class 名称的所有元素?
Is there a standard way to get all elements with a class name WITHIN a certain node?
我知道 Document.getElementsByClassname(String)
可以获取整个文档中特定 class 名称的所有元素。
我现在正试图在文档的特定节点中获取这些元素。在org.w3c.dom.Element
中,我只找到了getElementsByTagname
。我真的需要遍历所有这些元素并读取 class 名称,还是有更好的方法?
我试图找到一个仅使用 Java 的解决方案(可以与另一个库一起使用)。
非常感谢!
jQuery 是更好的方法。
这将选择 ID 为 "nodeToSearchName" 的节点中所有 class 为 "classNameToFind" 的节点。
$("#nodeToSearchName").find(".classNameToFind")
我最终使用了 JSoup,它包含我需要的方法。
http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#getElementsByClass%28java.lang.String%29
尽管您正在使用 org.w3c.dom.Document
个对象,但这也应该有效。
我在 Getting specific elements with XPath from an SVG with Batik 中找到了一个使用 xalan
库的解决方案。唯一的区别是我最终使用 XPathAPI
而不是 XPathEvaluator
因为 batik
与 org.w3c.dom.xpath.XPathEvaluator
实现不一致。
这是我写的代码的相关部分:
Element searchRoot= document.getRootElement();
NodeList nl = XPathAPI.selectNodeList(searchRoot, ".//*[@class=\"class_name\"]");
我知道 Document.getElementsByClassname(String)
可以获取整个文档中特定 class 名称的所有元素。
我现在正试图在文档的特定节点中获取这些元素。在org.w3c.dom.Element
中,我只找到了getElementsByTagname
。我真的需要遍历所有这些元素并读取 class 名称,还是有更好的方法?
我试图找到一个仅使用 Java 的解决方案(可以与另一个库一起使用)。
非常感谢!
jQuery 是更好的方法。
这将选择 ID 为 "nodeToSearchName" 的节点中所有 class 为 "classNameToFind" 的节点。
$("#nodeToSearchName").find(".classNameToFind")
我最终使用了 JSoup,它包含我需要的方法。
http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#getElementsByClass%28java.lang.String%29
尽管您正在使用 org.w3c.dom.Document
个对象,但这也应该有效。
我在 Getting specific elements with XPath from an SVG with Batik 中找到了一个使用 xalan
库的解决方案。唯一的区别是我最终使用 XPathAPI
而不是 XPathEvaluator
因为 batik
与 org.w3c.dom.xpath.XPathEvaluator
实现不一致。
这是我写的代码的相关部分:
Element searchRoot= document.getRootElement();
NodeList nl = XPathAPI.selectNodeList(searchRoot, ".//*[@class=\"class_name\"]");