【问题标题】:How to get the values of the same attribute of 3 nodes with the same name using XPath in Java?如何在Java中使用XPath获取3个同名节点的相同属性的值?
【发布时间】:2013-11-21 09:08:13
【问题描述】:

我有一个 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 表达式出错了。

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

    您要选择i-th sequenceFlow 节点的sourceRef 属性。使用这个:

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

    【讨论】:

    • 您需要将i 填充到查询字符串中。已更新我的答案。您使用哪种编程语言?
    • 我用的是JAVA,修改后还是一样的空行
    • xml 是否使用命名空间?
    • 我已经添加了我的 xml 文件
    • 您需要注册命名空间,然后使用命名空间访问元素。 xml 是什么类型的?
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多