[英]How to pass variable parameter into XPath expression?
I want to pass a parameter into an XPath expression. 我想将参数传递到XPath表达式中。
(//a/b/c[x=?],myParamForXAttribute)
Can I do this with XPath 1.0 ? 我可以使用XPath 1.0做到这一点吗? (I tried
string-join
but it is not there in XPath 1.0) (我尝试了
string-join
但XPath 1.0中没有它)
Then how can I do this ? 那我该怎么办呢?
My XML looks like 我的XML看起来像
<a>
<b>
<c>
<x>val1</x>
<y>abc</y>
</c>
<c>
<x>val2</x>
<y>abcd</y>
</c>
</b>
</a>
I want to get <y>
element value where x element value is val1
我想获取x元素值为
val1
<y>
元素值
I tried //a/b/c[x='val1']/y
but it did not work. 我尝试了
//a/b/c[x='val1']/y
但没有成功。
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: 假设您使用的是Axiom XPath库,而该库又使用Jaxen,则需要按照以下三个步骤以完全可靠的方式执行此操作:
context.setVariableValue("val", "value1")
to assign a value to that variable. context.setVariableValue("val", "value1")
为该变量分配一个值。 .setVariableContext()
to pass in the context you assigned. .setVariableContext()
以传入您分配的上下文。 /a/b/c[x=$val]/y
to refer to that value. /a/b/c[x=$val]/y
引用该值。 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. 这取决于您使用XPath的语言。
In XSLT: 在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; 请注意,与上面的方法不同,下面的三个对XPath注入攻击开放,决不能与不受控制或不受信任的输入一起使用。 to avoid this, use a mechanism provided by your language or library to pass in variables out-of-band.
为避免这种情况,请使用您的语言或库提供的机制来带外传递变量。 [ Credit : Charles Duffy]
[ 信用 :查尔斯达菲]
In C#: 在C#中:
String.Format("//a/b/c[x={0}]", myParamForXAttribute);
In Java: 在Java中:
String.format("//a/b/c[x=%s]", myParamForXAttribute);
In Python: 在Python中:
"//a/b/c[x={}]".format(myParamForXAttribute)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.