How to pass a variable parameter to an XPath expression?

I want to pass a parameter to an XPath expression.

(//a/b/c[x=?],myParamForXAttribute)

Can this be done with XPath 1.0? (I tried string-join, but it is not in XPath 1.0)

Then how can I do this?

My XML looks like

<a>
 <b>
  <c>
   <x>val1</x>
   <y>abc</y>
  </c>
  <c>
   <x>val2</x>
   <y>abcd</y>
  </c>
</b>
</a>

I want to get the value of an element <y>, where the value of element x isval1

I tried //a/b/c[x='val1']/y, but it did not work.

+2
source share
2 answers

Given that you are using the Axiom XPath library, which in turn uses Jaxen, you need to follow these three steps to do this with complete reliability:

  • Create a SimpleVariableContext and call the context.setVariableValue("val", "value1")value for this variable to assign.
  • 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());
    }
}

... :

abcd
+4

, XPath.

XSLT:

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

, XPath- ; , , , . [ : ]

#:

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

Java:

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

Python:

 "//a/b/c[x={}]".format(myParamForXAttribute)
+4

Source: https://habr.com/ru/post/1589108/


All Articles