Key words: Jdom XPath xmlns namespace openjweb
Locating nodes with XPath in Jdom is usually in the following ways:
XPath Xpath=null;
Element anode = null;
Saxbuilder sb = new Saxbuilder ();
Document doc = null;
Try
{
doc = Sb.build ("Xxx.xml");
}
catch (Exception ex)
{
Return "Parsing XML failed!";
}
XPath = xpath.newinstance ("/Node 1/node 2[@ attribute 1 = ' value 1 ']");
Anode= (Element) Xpath.selectsinglenode (DOC);
However, when dealing with spring bean files, it is found that this method does not locate the node you are looking for, the following is Openjweb's Core-service-demo.xml, now to find the hibernate configuration in this file, file format:
<?xml version= "1.0" encoding= "GB2312"?>
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
......
<bean id= "Demosessionfactory"
class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<property name= "DataSource" >
<ref local= "Demodatasource"/>
</property>
<property name= "Mappingresources" >
<list>
<value>org/openjweb/core/entity/CommSubSystem.hbm.xml</value>
......
</list></property>
</bean>
</beans>
Now you want to find the list node through the program, but find the element without the list in the following way:
XPath = xpath.newinstance ("/beans/bean/property[@name = ' mappingresources ']/list");
Anode = (Element) Xpath.selectsinglenode (DOC);
The solution was later found on the web because the beans root node had an xmlns namespace. To register the namespace, see the following code:
XPath = xpath.newinstance ("/ns:beans/ns:bean/ns:property[@name = ' mappingresources ']/ns:list");
NS is a random name.
Xpath.addnamespace ("ns", "Http://www.springframework.org/schema/beans");
Anode = (Element) Xpath.selectsinglenode (DOC);
An NS namespace is defined above, and in addition to the XPath lookup string, each level node is incremented by NS: In this way, the list node can be found.