[JAVA] `SAXReader`: Get the xml file with the default namespace set in XPath format

environment

pom.xml


<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.1</version>
</dependency>

Thing you want to do

I want to get the XML with the default namespace set as below in XPath format.

web.xml


<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
  <context-param>
    <param-name>version</param-name>
    <param-value>1.2.3</param-value>
  </context-param>
 </web-apps>

Now I want to get the value 1.2.3 in the<param-value>element, which corresponds to the key version in the <param-name> element.

What I tried

The code below returned an empty string and couldn't get the value 1.2.3.

Bad.java


 BaseXPath xpath = new Dom4jXPath("//context-param/param-name[text()='version']/following-sibling::param-value");
String version = xpath.stringValueOf(doc); //⇒ Empty string

The method that was realized

You need to set the default namespace yourself.

Good.java


 //Default namespace"p"Prefix with.
BaseXPath xpath = new Dom4jXPath(//p:context-param/p:param-name[text()='version']/following-sibling::p:param-value");
xpath.addNamespace("p", "http://java.sun.com/xml/ns/j2ee");
String version = xpath.stringValueOf(doc); //⇒1.2.3

Reference site

http://waman.hatenablog.com/entry/20091030/1256858160 http://www.edankert.com/defaultnamespaces.html#What_s_the_Problem_

Recommended Posts

`SAXReader`: Get the xml file with the default namespace set in XPath format
[Java] Get the file path in the folder with List
[Java] Get the file in the jar regardless of the environment
Format XML in Java
Put the file in the properties of string in spring xml configuration
Overwrite bean definition in spring xml configuration file with another xml
In Redmine you can get the project with Project.find (<identifier>)
Get attributes and values from an XML file in Java
[Problem solving] SAXReader: How to read an xml file with an external DTD file specified in an offline environment
Fix the file name of war to the one set in Maven
Get the public URL of a private Flickr file in Java
How to get the length of an audio file in java