How to pass variable parameter into XPath expression?

China☆狼群 提交于 2019-11-26 15:33:42

Given that you're using the Axiom XPath library, which in turn uses Jaxen, you'll need to follow the following three steps to do this in a thoroughly robust manner:

  • Create a SimpleVariableContext, and call context.setVariableValue("val", "value1") to assign a value to that variable.
  • On your BaseXPath object, call .setVariableContext() to pass in the context you assigned.
  • Inside your expression, use /a/b/c[x=$val]/y to refer to that value.

Consider the following:

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());
    }
}

...which emits as output:

abcd

It depends on the language in which you're using XPath.

In XSLT:

 "//a/b/c[x=$myParamForXAttribute]"

Note that, unlike the approach above, the three below are open to XPath injection attacks and should never be used with uncontrolled or untrusted inputs; to avoid this, use a mechanism provided by your language or library to pass in variables out-of-band. [Credit: Charles Duffy]

In C#:

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

In Java:

String.format("//a/b/c[x=%s]", myParamForXAttribute);

In Python:

 "//a/b/c[x={}]".format(myParamForXAttribute)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!