【问题标题】:Simple dom4j parsing in Java - can't access child nodesJava中的简单dom4j解析-无法访问子节点
【发布时间】:2015-11-18 05:13:21
【问题描述】:

我知道这很容易,我整天都在敲我的头。我有一个这样的 XML 文档:

<WMS_Capabilities version="1.3.0" xmlns="http://www.opengis.net/wms">
<Service>
<Name>WMS</Name>
<Title>Metacarta WMS VMaplv0</Title>
</Service>
<Capability>
<Layer>
<Name>Vmap0</Name>
<Title>Metacarta WMS VMaplv0</Title>
<Abstract>Vmap0</Abstract>
...

可以有多个Layer节点,任何Layer节点都可以有嵌套的Layer节点。我可以快速选择所有层节点并使用以下 xpath 代码遍历它们:

Map<String, String> uris = new HashMap<String, String>();
uris.put("wms", "http://www.opengis.net/wms");
XPath xpath1 = doc.createXPath("//wms:Layer");
xpath1.setNamespaceURIs(uris);
List nodes1 = xpath1.selectNodes(doc);

for (Iterator<?> layerIt = nodes1.iterator(); layerIt.hasNext();) {
            Node node = (Node) layerIt.next();
}

我取回所有图层节点。完美的。但是当我尝试访问每个 Name 或 Title 子节点时,我什么也得不到。我尝试了尽可能多的各种组合:

name = node.selectSingleNode("./wms:Name");
name = node.selectSingleNode("wms:Name");
name = node.selectSingleNode("Name");

etc 等,但它总是返回 null。我猜它与命名空间有关,但我所追求的只是我获得的每个图层节点的名称和标题文本值。任何人都可以提供任何帮助:

【问题讨论】:

  • 试试node.selectSingleNode("*:Name")

标签: java xml xpath dom4j


【解决方案1】:

我相信 Node.selectSingleNode() 使用空的命名空间上下文评估提供的 XPath 表达式。因此,无法按名称访问没有命名空间中的节点。必须使用*[local-name='Name'] 等表达式。如果您想要/需要命名空间上下文,请通过 XPath 对象执行 XPath 表达式。

【讨论】:

  • 不幸的是,当我使用 *[local-name='Name']... 时它仍然返回 null... 即 Node name = node.selectSingleNode("*[local-name='Name']") ;我不知道如何正确使用 xpath 对象。当我过去完成它时,它总是访问结果中的第一个 Layer 对象。考虑到我正在迭代的当前节点,我不知道如何使用 XPath 对象。
  • 好吧,恐怕我不是 dom4j 专家。但是 xpath.selectNodes 接受一个节点参数,该参数用作评估 XPath 表达式的上下文项。
  • 感谢您的帮助——您肯定让我走上了正确的道路,所以我赞成您的回答。
【解决方案2】:

感谢大家的帮助。这是 Michael Kay 为我找到的最后一条线索……我需要使用来自当前节点的相对路径,包括命名空间 URI,并从我正在迭代的当前节点的上下文中进行选择:

Map<String, String> uris = new HashMap<String, String>();
uris.put("wms", "http://www.opengis.net/wms");
XPath xpath1 = doc.createXPath("//wms:Layer");
xpath1.setNamespaceURIs(uris);
List nodes1 = xpath1.selectNodes(doc);

for (Iterator<?> layerIt = nodes1.iterator(); layerIt.hasNext();) {
    Node node = (Node) layerIt.next();
    XPath nameXpath = node.createXPath("./wms:Name");
    nameXpath.setNamespaceURIs(uris);
    XPath titleXpath = node.createXPath("./wms:Title");
    titleXpath.setNamespaceURIs(uris);
    Node name = nameXpath.selectSingleNode(node);
    Node title = titleXpath.selectSingleNode(node);
}

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多