开发者

Searching part of a String using XPath query

开发者 https://www.devze.com 2023-02-26 13:02 出处:网络
I am using the following XPath query to search the name of the author of a book and return the book name when it matches the author.

I am using the following XPath query to search the name of the author of a book and return the book name when it matches the author.

String rawXPath = String.format("//book[author= '%s']/bookname/text()", authorBook);  

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr 
 = xpath.compile(rawXPath);

Object result = expr.evaluate(doc, XPathConstan开发者_开发百科ts.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue()); 
}

how to modify the search so that I can search in the content ...../content(node name) for a specific word.

Example: String inside the xml content variable: "This book contains the glory and history of our forefathers. And the impact of it in our daily life is immense."

Now I want to search for the word "daily". If it matches daily it will retun me the book name/author name watever the user wants.

Thanks


Use the contains() Xpath function.

//book[contains(content, '%s')]/bookname

depending a bit of the structure of you input XML


You want:

//book[contains(content, $searchString)
     and
       author = $wantedAuthor
      ]
       /bookname/text()

This selects the text() nodes that are children of the bookname element that is a child of any book element in the document, the string value of whose content child contains the string (contained in) $searchString and the string value of whose author element is the same as the (string contained in) $wantedAuthor variable

In this Xpath expression the variables need to be substituted by specific strings. Also, it assumes that the element content is a child of book.

I don't know Java, but suppose that the final Java code wil look like the following:

String.format("//book[contains(content, '%s') 
                    and 
                     author= '%s']/bookname/text()", 
              searchString, authorBook);   


if your xml looks like this:

 <book>
   <author> Author Name </author>
   <description> This book contains the glory and history of our forefathers. And the impact of it in our daily life is immense.</description>
 </book>

then you can try:

String rawXPath = "//book//*[contains(text(),\"daily\")]";

which means "give any book element that any child holds a text that contains the word 'daily'.

I hope that helps you out! cheers!


Now if u want to search also some term which is inside one node u can do it like this -

String rawXPath = String.format("//book/title[contains(innerItem, '%s')]/type/text()", value);

Add one backslash for each node and the node name and ur in.

0

精彩评论

暂无评论...
验证码 换一张
取 消