无法在 Xerces 或 Neko 中的节点上调用 getElementsByTagName?

发布于 2024-09-11 09:15:11 字数 601 浏览 2 评论 0原文

大家好,我正在尝试使用 Java 中的 Neko/Xerces 解析 DOM 树。

NodeList divs = this.doc.getElementsByTagName("DIV");
for(int i=0; i < divs.getLength(); i++) {
    NodeList images = divs.item(i).parentNode().getElementsByTagName("IMG");
    // operate on these
}

这就是我理想中想做的事情。看来我只能在文档本身上调用 getElementsByTagName ?我做错了什么吗?我应该能够在 Node 元素上调用它吗?

我可以从文档中看到它不存在: http:// /xerces.apache.org/xerces-j/apiDocs/org/w3c/dom/Node.html 所以也许我需要用另一种方式来做?

谢谢!

hi all I'm trying to parse a DOM tree using Neko/Xerces in Java.

NodeList divs = this.doc.getElementsByTagName("DIV");
for(int i=0; i < divs.getLength(); i++) {
    NodeList images = divs.item(i).parentNode().getElementsByTagName("IMG");
    // operate on these
}

is what I'd ideally like to do. It seems I can only call getElementsByTagName on the document itself? Am I doing something wrong? Should I be able to call that on a Node element?

I can see from the docs it's not there: http://xerces.apache.org/xerces-j/apiDocs/org/w3c/dom/Node.html so maybe I need to do it another way?

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

池木 2024-09-18 09:15:12

是的,这很奇怪。 Python 的 xml.dom.minidom 有一个 Node.getElementsByTagName。也许它不是标准的一部分。相反,您可以在 divs.item(i).parentNode().getChildNodes() 上迭代内部循环。

Yeah, that's weird. Python's xml.dom.minidom has a Node.getElementsByTagName. Maybe it's not part of the standard. Instead, you could iterate an inner loop over divs.item(i).parentNode().getChildNodes().

两仪 2024-09-18 09:15:11

NodeList 仅返回节点,并且 getElementsByTagName 仅在 元素节点 因此,您需要将节点转换为元素,下面是一个示例。

final NodeList images = ((Element)divs.item(i).getParentNode()).getElementsByTagName("IMG");

但是要小心这一点,因为它假设 getParentNode() 总是返回一个 Element

这会更安全,但更冗长

final Node n = divs.item(i).getParentNode();

if(n instanceof Element) {
    final Element e = (Element)n;
    e.getElementsByTagName("IMG");
}

A NodeList only returns Nodes and getElementsByTagName is only available on an Element node You therefore need to cast your Node to an element, here's an example below.

final NodeList images = ((Element)divs.item(i).getParentNode()).getElementsByTagName("IMG");

However be careful with this as it assumes that getParentNode() always returns an Element

This would be safer, but a lot more verbose

final Node n = divs.item(i).getParentNode();

if(n instanceof Element) {
    final Element e = (Element)n;
    e.getElementsByTagName("IMG");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文