如何将变量参数传递到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看起来像
<a>
<b>
<c>
<x>val1</x>
<y>abc</y>
</c>
<c>
<x>val2</x>
<y>abcd</y>
</c>
</b>
</a>
我想获得x元素值为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());
}
}
...作为输出发出:
...which emits as output:
abcd
这篇关于如何将变量参数传递到XPath表达式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文