简体   繁体   中英

java xpath XML parsing

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);

如果使用XPath 2.0实现,则可以使用tokenize并使用正则表达式按逗号分隔字符串,然后选择第二个标记:

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

我不认为这是可能的,这可能不是一个好主意,你的元素的内容应该是原子的,我会避免将这个解析与Xpath混合,并简单地用一个实用方法包装事件来装饰第一个单词。

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