Hi there,
I've tried to parse web.xml file with dom4j - XPATH but failed. The xml file
is listed below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 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">
<context-param>
<param-name>name</param-name>
<param-value>this is the context param value</param-value>
</context-param>
<servlet>
<servlet-name>TestServlet1</servlet-name>
<servlet-class>TestServlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>TestServlet2</servlet-name>
<servlet-class>TestServlet2</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
</web-app>
And below is the java Code:
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class TestDom4j {
public static void main(String[] args) throws DocumentException {
SAXReader reader = new SAXReader();
Document dom = reader.read("web.xml");
Node node = dom.selectSingleNode("//context-param/param-name");
System.out.println(node.getText());
String value = dom.valueOf("//context-param/param-value");
System.out.println(value);
System.out.println("-----------------------------------");
List<Node> list = dom.selectNodes("//servlet");
for (Node node2 : list) {
String name2 = node2.valueOf("servlet-name");
String value2 = node2.valueOf("servlet-class");
System.out.println(name2 + ":" + value2);
}
}
}
And it can't get the correct result. Node 'context-param' or 'servlet' can't
be parsed with xpath like this.
However if I modified the root node to <web-app version="2.4"> or <web-app>
the code will work.
And I tried to parse the child nodes one by one without domj4 like this:
for (Iterator<Element> iterator = root.elementIterator("context-param");
iterator
.hasNext();)
....
It works.
So my question is: why can't we use xpath to parse the xml file with the
'xmlns' attribute exists in root node? If we can use xpath to parse it, how
to do that?
Thanks in advance.
------------------------------------------------------------------------------
The Planet: dedicated and managed hosting, cloud storage, colocation
Stay online with enterprise data centers and the best network in the business
Choose flexible plans and management services without long-term contracts
Personal 24x7 support from experience hosting pros just a phone call away.
http://p.sf.net/sfu/theplanet-com
_______________________________________________
dom4j-user mailing list
dom4j-user@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/dom4j-user