I need to filter many XML files like this:
<header>
<type>1</type>
<time>today</time>
</header>
<message>
<Event...>
<Counter...>
...
</message>
I need to pick only all the message content whose header.type == 1. I'm reading from multiple files I need to select the message content with type == 1.
I've just little updated your XML-structure to be well-formed. Here are several XML files for testing:
========= one.xml ==========
<root>
<header>
<type>1</type>
</header>
<message>right</message>
</root>
========= two.xml ==========
<root>
<header>
<type>1</type>
</header>
<message>right</message>
</root>
========= three.xml ==========
<root>
<header>
<type>2</type>
</header>
<message>wrong</message>
</root>
And simple code looks like this:
import java.io.File;
import static org.joox.JOOX.$;
public class JooxDemo {
public static void main(String[] args) throws Exception {
final File dirWithXmls = new File("xmls");
for (File xmlFile : dirWithXmls.listFiles()) {
final String message = $(xmlFile).xpath("//header[type='1']/../message").text();
System.out.println(xmlFile.getName() + ", message: " + message);
}
}
}
Output:
one.xml, message: right
three.xml, message: null
two.xml, message: right
As you can see message has been fetched only in case if header is of type 1.
Therefore you can delete .text()
and do what you need with message node after simple not-null check.