Bax995961
Bax995961

Reputation: 35

Full-text-search in a xml file with java (with Xpath?)

is there a possibility to perform a full text search in a xml file with Xpath and select them using java? I want to select all elements (no mater if it is a comment, node or attribute), which contains a special word. For example: Searching for "bob" I would like to get tag1, bob1 and tag3 as a result

<tag1 name="bob">
    <tag2/>
    <bob1/>
    <tag3 bob="true"/>
</tag1>

If it is possible, I prefer a solution without using an external package. I would be very happy if somebody could help me. I couldn't find anything like this until now. Thank you very much! Kind regards

EDIT: I am searching for a possibility to finde every occurrence of the word "Bob", no matter what function Bob has!

Upvotes: 1

Views: 1975

Answers (2)

Mike Sokolov
Mike Sokolov

Reputation: 7054

XPath defines the contains() function (see http://www.w3.org/TR/xpath/#function-contains) which you could use in an expression like:

//*[contains(., "wordtosearchfor")]

which would find all elements containing the word

To find all attributes containing the word, you could use:

//*[@*[contains(., "wordtosearchfor")]]

which would find all elements having an attribute containing the word

However the problem as you stated it is not well-posed. The XML sample you gave is not well-formed, and it is not true that contains "bob". So it's hard to tell exactly what you are trying to do.

Upvotes: 1

gaborsch
gaborsch

Reputation: 15758

You can write a simple SAX parser to process your XML. Here's the Oracle SAX tutorial for starting.

You can go through all nodes, mark (and save) those nodes that are interesting for you, and return the resulting nodes as a new XML document, or String, or whatever form you want.

Upvotes: 1

Related Questions