XML 構造を適切な形式に少し更新しました。テスト用のいくつかの XML ファイルを次に示します。
========= 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>
簡単なコードは次のようになります。
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);
}
}
}
出力:
one.xml, message: right
three.xml, message: null
two.xml, message: right
ご覧のとおり、ヘッダーがタイプ1の場合にのみ、メッセージがフェッチされています。
したがって、単純な not-null チェックの後、メッセージ.text()ノードを削除して必要なことを行うことができます。