如何在Java中使用XPath获取具有相同名称的3个节点的相同属性的值?

时间:2013-11-21 09:08:13

标签: java xml xpath

我有以下XML文件节点:

<definitions 
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" 
  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" 
  xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" 
  xmlns:di="http://www.omg.org/spec/DD/20100524/DI" 
  xmlns:tns="http://www.jboss.org/drools" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" 
  id="Definition" 
  targetNamespace="http://www.example.org/MinimalExample" 
  typeLanguage="http://www.java.com/javaTypes" 
  expressionLanguage="http://www.mvel.org/2.0" 
  xs:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"
>
  <process processType="Private" isExecutable="true" id="com.sample.HelloWorld" name="Hello World">
    <!-- nodes -->
    <startEvent id="_1" name="StartProcess" />
    <scriptTask id="_2" name="Hello">
      <script>System.out.println("Hello World");</script>
    </scriptTask>
    <endEvent id="_3" name="EndProcess">
      <terminateEventDefinition />
    </endEvent>
    <!-- connections -->
    <sequenceFlow id="_1-_2" sourceRef="_1" targetRef="_2" />
    <sequenceFlow id="_2-_3" sourceRef="_2" targetRef="_3" />
  </process>
</definitions>

我想使用XPath获取每个sequenceFlow节点的sourceRef属性的所有值。

我构建了一个for循环:

if (n.getNodeName().equals("sequenceFlow")) {
    countsequenceFlows ++;

    for (int i=0; i<=countsequenceFlows;i++) {
        sourceRef = xml.getParameterString("(//sequenceFlow/@sourceRef)[i]");
        System.out.println(sourceRef);
    }
}

但我在输出中没有得到任何东西。我想我的XPath表达式出错了。

1 个答案:

答案 0 :(得分:0)

您想要选择sourceRef - i节点的sequenceFlow属性。使用此:

sourceRef = xml.getParameterString("//sequenceFlow[" + i + "]/@sourceRef");