Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

regex - using regular expressions in xpath and xml

i have a small problem in using regular expressions along with xml and xpath.

I have an xml file like this

messages.xml

<message>
  <text>dog goes woof</text>
</message>
<message>
  <text>cat goes meow, dog goes woof, fish goes blub</text>
</message>

and then i have an xpath expression which allows me to select the text node which has text node as dog goes woof like this

   String expression = "//text[.='dog goes woof']";
   NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(messages, XPathConstants.NODESET);

here "messages" is the Document variable which refers to the messages.xml file.

when i iterate through the nodeList, it selects only the first text node. I want to select the other text node too which contains dog goes woof. So how can i specify in the xpath expression to check for text nodes which contains dog goes woof in them.

please let me know how to do it.

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use the contains() function or if you really want to use regex you can use the matches() function

"//text[contains(text(), 'dog goes woof')]"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...