如何将变量参数传递到XPath表达式中?

use*_*734 2 xml xpath axiom xpath-1.0

我想将参数传递到XPath表达式中。

(//a/b/c[x=?],myParamForXAttribute)
Run Code Online (Sandbox Code Playgroud)

我可以使用XPath 1.0做到这一点吗?(我尝试过,string-join但XPath 1.0中没有)

那我该怎么办呢?

我的XML看起来像

<a>
 <b>
  <c>
   <x>val1</x>
   <y>abc</y>
  </c>
  <c>
   <x>val2</x>
   <y>abcd</y>
  </c>
</b>
</a>
Run Code Online (Sandbox Code Playgroud)

我想获得<y>x元素值为的元素值val1

我尝试过,//a/b/c[x='val1']/y但是没有用。

Cha*_*ffy 6

假设您使用的是Axiom XPath库,而该库又使用Jaxen,则需要按照以下三个步骤以完全健壮的方式执行此操作:

  • 创建一个SimpleVariableContext,并调用context.setVariableValue("val", "value1")将值分配给该变量。
  • BaseXPath对象上,调用.setVariableContext()以传递您分配的上下文。
  • 在表达式内部,用于/a/b/c[x=$val]/y引用该值。

考虑以下:

package com.example;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.common.AxiomText;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axiom.om.xpath.DocumentNavigator;
import org.jaxen.*;

import javax.xml.stream.XMLStreamException;

public class Main {

    public static void main(String[] args) throws XMLStreamException, JaxenException {
        String xmlPayload="<parent><a><b><c><x>val1</x><y>abc</y></c>" +
                                        "<c><x>val2</x><y>abcd</y></c>" +
                          "</b></a></parent>";
        OMElement xmlOMOBject = AXIOMUtil.stringToOM(xmlPayload);

        SimpleVariableContext svc = new SimpleVariableContext();
        svc.setVariableValue("val", "val2");

        String xpartString = "//c[x=$val]/y/text()";
        BaseXPath contextpath = new BaseXPath(xpartString, new DocumentNavigator());
        contextpath.setVariableContext(svc);
        AxiomText selectedNode = (AxiomText) contextpath.selectSingleNode(xmlOMOBject);
        System.out.println(selectedNode.getText());
    }
}
Run Code Online (Sandbox Code Playgroud)

...作为输出发出:

abcd
Run Code Online (Sandbox Code Playgroud)


kjh*_*hes 5

这取决于您使用XPath的语言。

在XSLT中:

 "//a/b/c[x=$myParamForXAttribute]"
Run Code Online (Sandbox Code Playgroud)

请注意,与上面的方法不同,下面的三个对XPath注入攻击开放,决不能与不受控制或不受信任的输入一起使用。为避免这种情况,请使用您的语言或库提供的机制来带外传递变量。 [ 信用:查尔斯达菲]

在C#中:

String.Format("//a/b/c[x={0}]", myParamForXAttribute);
Run Code Online (Sandbox Code Playgroud)

在Java中:

String.format("//a/b/c[x=%s]", myParamForXAttribute);
Run Code Online (Sandbox Code Playgroud)

在Python中:

 "//a/b/c[x={}]".format(myParamForXAttribute)
Run Code Online (Sandbox Code Playgroud)