Question

I've written some code to extract different parts of from an XML string using xpath. The question I have is if the xml string was for example

<event>alarm, red, 2</event>

is there any easy way with xpath to select say the second word in the string after the first comma so "red"?? right now i am using

String event = xpath.evaluate("/event", doc);

which returns "alarm, red, 2" but all i want is "red". I know that i could just then take event and use substring to extract "red" but i am wondering if there is a way to do this using xpath rather than substring?

code:

String xml = "<event>alarm, red, 2<event>";  

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(xml));
Document doc = (Document) xpath.evaluate ("/", source, XPathConstants.NODE);
Was it helpful?

Solution

If you use an XPath 2.0 implementation, you can use tokenize and use a regular expression to split the string by the comma and then select the second token:

tokenize(/event, ',')[2]

OTHER TIPS

I don't think it's possible & it's probably not a good idea to do that, content of your element is supposed to be atomic, I would avoid mixing this parsing with Xpath and simply wrap the event with a utility method garbing the first word.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top