如何将可变参数传递给 XPath 表达式? [英] How to pass variable parameter into XPath expression?
本文介绍了如何将可变参数传递给 XPath 表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将参数传递给 XPath 表达式.
I want to pass a parameter into an XPath expression.
(//a/b/c[x=?],myParamForXAttribute)
我可以用 XPath 1.0 做到这一点吗?(我尝试了 string-join
但它在 XPath 1.0 中没有)
Can I do this with XPath 1.0 ? (I tried string-join
but it is not there in XPath 1.0)
那我该怎么做呢?
我的 XML 看起来像
My XML looks like
<a>
<b>
<c>
<x>val1</x>
<y>abc</y>
</c>
<c>
<x>val2</x>
<y>abcd</y>
</c>
</b>
</a>
我想获得
元素值,其中 x 元素值为 val1
I want to get <y>
element value where x element value is val1
我尝试了 //a/b/c[x='val1']/y
但没有奏效.
I tried //a/b/c[x='val1']/y
but it did not work.
推荐答案
鉴于您使用的是 Axiom XPath 库,而后者又使用 Jaxen,您需要按照以下三个步骤彻底完成此操作稳健的方式:
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:
- 创建一个 SimpleVariableContext,并调用
context.setVariableValue("val", "value1")
为该变量赋值. - 在您的 BaseXPath 对象上,调用
.setVariableContext()
传入您分配的上下文. - 在表达式中,使用
/a/b/c[x=$val]/y
来引用该值.
- 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.
考虑以下事项:
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());
}
}
...作为输出发出:
abcd
这篇关于如何将可变参数传递给 XPath 表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文