Java中简单的dom4j解析 - 无法访问子节点

时间:2014-04-02 20:31:58

标签: java xml xpath dom4j

我知道这很容易,而且我整天都在敲我的脑袋。我有一个这样的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();
}

我找回所有Layer节点。完善。但是当我尝试访问每个Name或Title子节点时,我什么也得不到。我尝试了许多我能想到的各种组合:

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

感谢大家的帮助。这是迈克尔凯的最后一条线索,它让我...我需要使用当前节点的相对路径,包括命名空间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);
}