依赖包:
dom4j-1.6.1, jaxen -1.1.1
xml:
<?xml version="1.0" encoding="UTF-8"?>
<mapper
namespace="com.demo.User"
xmlns="http://www.nl.org/mapper"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nl.org/mapper">
<select id="list">
select * from user u where 1=1
<if property="id" notNull="">
and u.id=#id
</if>
<if property="name" notNull="">
and u.name like '%#name%'
</if>
</select>
<update id="update">
update user u set u.name=$name
<if property="sex" notNull="">
,u.sex=$sex
</if>
where u.id=#id
</update>
</mapper>
java类部份解析代码:
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(file);
HashMap map = new HashMap();
map.put( "tns", "http://www.nl.org/mapper");
XPath xpath = document.createXPath( "//tns:mapper");
xpath.setNamespaceURIs(map);
Element rootElement= (Element) xpath.selectSingleNode( document);