简体   繁体   中英

Dynamically assign value to xpath expression in java

I am trying to create gui dynamically from WSDL file by using java. I need to retrieve the messages related with each operation. For that i need to assign the XPath expression value dynamically. I assign the expression as follows

  String expression="/definitions/portType/operation[@name="+oper[i]+"]/*";
  NodeList msglist=    (NodeList)xpath.expressionxpath.compile(expression1).evaluate(doc,XPathConstants.NODESET);
  System.out.println("The Number of messages are"+msglist.getLength());

Here oper[i] is the array containing list of operation names. But it is not working when I print the number of nodes in the msglist it always displays 0. My WSDL file contains 2 child element for operation element. Anyone can Helpme?? Thanks in advance

From the comments, the pattern is:

/definitions/portType/opeation[@name=sayHello]/*

Quotes around the match string are missing. It should be:

/definitions/portType/opeation[@name="sayHello"]/*

So your pattern should be:

String expression="/definitions/portType/operation[@name=\""+oper[i]+"\"]/*";

It might be clearer to use a MessageFormat or String.format :

String expression=String.format("/definitions/portType/operation[@name=\"%s\"]/*", oper[i]);

Your error is the missing quotes. However, you should try to avoid constructing XPath expressions by string concatenation, for at least three reasons:

  • It's easy to make mistakes like the one you made

  • There's a grave danger of leaving yourself open to code injection attacks

  • Performance

Instead, take advantage of the fact that XPath expressions can contain variable references:

String expression="/definitions/portType/operation[@name=$param]/*";

and that you can bind a value to the variable when executing the expression. The JAXP mechanism for this (defining a VariableResolver) isn't especially elegant, but it's easy enough to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM