2013-11-21 86 views
-1

我有一個XML文件的以下節點:如何使用Java中的XPath獲取具有相同名稱的3個節點的相同屬性的值?

<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表達式中犯了一個錯誤。

回答

0

您想要選擇i節點的sourceRef屬性。使用這個:

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

我試過這個,但我仍然得到一個空行輸出 – user2966458

+0

你需要填充'i'到查詢字符串。已經更新了我的答案。你使用的是什麼編程語言? – hek2mgl

+0

我正在使用JAVA,即使在修改後我也會得到相同的空白行 – user2966458

相關問題