XPath获取属性具有特定值的节点的名称

时间:2016-11-17 11:49:24

标签: java xpath

我有以下XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="20131001" xmlns:xmi="http://www.omg.org/spec/XMI/20131001" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SecureUML="http://RootElement/schemas/SecureUML/_zVWe83m5Eeae1LmHHETvPg/99" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:uml="http://www.eclipse.org/uml2/5.0.0/UML" xsi:schemaLocation="http://RootElement/schemas/SecureUML/_zVWe83m5Eeae1LmHHETvPg/99 ../SecureUML/SecureUML.profile.uml#_zVWe9Hm5Eeae1LmHHETvPg">
...
<SecureUML:Role xmi:id="_6l9aEKgBEea49okOlb9Hog" base_Classifier="_0YCfQKgBEea49okOlb9Hog"/>
<SecureUML:Role xmi:id="_7aToIKgBEea49okOlb9Hog" base_Classifier="_3xegQKgBEea49okOlb9Hog"/>

如何获取base_Classifier所在节点的名称,例如_0YCfQKgBEea49okOlb9Hog_3xegQKgBEea49okOlb9Hog?这两个字符串我将它们放在ArrayList中,所以我的确如此:

String tmp = items.get(j).getId();
String stereotypes = "//*[@base_Classifier="+tmp+"]";  
NodeList nodeList1 = (NodeList) xpath.compile(stereotypes)
    .evaluate(doc, XPathConstants.NODESET); 

nodeList1为空。

我提到我希望_0YCfQKgBEea49okOlb9Hog_3xegQKgBEea49okOlb9Hog都获得SecureUML:Role

我还提到我使用像

这样的smth注册名称空间
HashMap<String, String> prefMap = new HashMap<String, String>() {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

     {
         put("xmi", "http://www.omg.org/spec/XMI/20131001");
         put("SecureUML", "http://RootElement/schemas/SecureUML/_zVWe83m5Eeae1LmHHETvPg/99");
     }
};

非常感谢提前!

Madalina

1 个答案:

答案 0 :(得分:0)

您的XPath谓词不正确,因为您的属性类型显然是String而不是Number,因此您需要将属性的值置于双倍或单一之间引号,然后调用getNodeName()获取节点的名称,如下所示:

String stereotypes = String.format("//*[@base_Classifier=\"%s\"]", tmp);
NodeList nodeList1 = (NodeList) xpath.compile(stereotypes)
   .evaluate(doc, XPathConstants.NODESET);
System.out.println(nodeList1.item(0).getNodeName());

<强>输出:

SecureUML:Role