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>
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.
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
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
http://waman.hatenablog.com/entry/20091030/1256858160 http://www.edankert.com/defaultnamespaces.html#What_s_the_Problem_
Recommended Posts