dom4j和xpath解析带名称空间的xml…

来源:互联网 发布:国家的崛起人工智能 编辑:程序博客网 时间:2024/06/10 08:55
 

首先以spring的配置文件applicationContext.xml为例:

 



 package cn.itcast.dom4j;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.junit.Test;
public class NamespaceParseXml {
 @Test
 public void getSingleValue() {
  SAXReader reader = new SAXReader();
  try {
   Document document = reader.read(new File("src/persistence.xml"));
   Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
   // 设置一个命名空间,其中put中的key可任意取名(符合Java命名规范),value为一个uri;
   nsMap.put("key", "http://java.sun.com/xml/ns/persistence");
   // 创建一个xpath表达式,xmlns为上面设置的key;两者必须相同;否则会报错;xpath表达式参看文档;
   XPath xPath = document
     .createXPath("//key:persistence//key:persistence-unit//key:properties//key:property");
   // 将设置好的命名空间集合交给xpath对象,使其内部和文档进行匹配和解析;
   xPath.setNamespaceURIs(nsMap);
   // 用匹配好的名称空间的xpath表达式选取所需的节点做进一步的操作;
   String value = xPath.selectSingleNode(document).getText();
   System.out.println(value);
  } catch (DocumentException e) {
   throw new RuntimeException(e);
  }
 }
 // 使用xpath和namespace进行文档的快速查找,查找出applicationContext.xml文档中;
 // 所有id属性值;并打印输出;
 @Test
 public void getAllId() throws DocumentException {
  // 1 创建SAXReader;
  SAXReader reader = new SAXReader();
  // 通过解析器解析出xml文档对应的文档对象Docment;
  Document document = reader.read("src/applicationContext.xml");
  // 设置命名空间;
  Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
  nsMap.put("xmlns", "http://www.springframework.org/schema/beans");
  // 创建xpath表达式,并将该表达式封装成XPath对象;
  XPath xPath = document.createXPath("//@id");
  // 实际上这里可以不用nsMap, 为创建xpath表达式时没有用到名称空间namespace;
  xPath.setNamespaceURIs(nsMap);
  // 用封装好的xpath对象表达式去搜索文档对象中需要的东西;
  List<Attribute> nodes = xPath.selectNodes(document);
  for (Attribute attribute : nodes) {
   System.out
     .println(attribute.getName() + "=" + attribute.getValue());
  }
 }
 @Test
 public void getAllBean() {
  try {
   // 通过解析器获取xml对应的Document对象;
   SAXReader reader = new SAXReader();
   Document document = reader.read("src/applicationContext.xml");
   // 创建名称空间的集合;
   Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
   nsMap.put("xmlns", "http://www.springframework.org/schema/beans");
   // 创建xpath表达式对象;
   XPath xpath = document.createXPath("//xmlns:bean");
   // 将名称空间注入到xpath中;
   xpath.setNamespaceURIs(nsMap);
   // 用xpath表达式对文档进行搜索;获取需要的节点对象;
   List<Element> elements = xpath.selectNodes(document);
   //为了提高程序的健壮性,对参数进行判断,避免空指针问题;
   if (elements != null) {
    for (Element element : elements) {
     List<Attribute> list = element.attributes();
     if (list != null) {
      for (Attribute attribute : list) {
       System.out.println(attribute.getName() + "=="
         + attribute.getValue());
      }
     }
    }
   }
  } catch (DocumentException e) {
   throw new RuntimeException(e);
  }
 }
}

applicationContext.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/context/spring-tx.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">
 <context:component-scan base-package="cn.itcast" />
 <aop:aspectj-autoproxy />
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url"
   value="jdbc:mysql://localhost:3306/jdbc?userUnicode=true&amp;characterEncoding=UTF-8" />
  <property name="username" value="root" />
  <property name="password" value="123456" />
  <property name="initialSize" value="10" />
  <property name="maxActive" value="50" />
  <property name="maxIdle" value="20" />
  <property name="minIdle" value="5" />
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mappingResources">
   <list>
    <value>cn/itcast/domain/User.hbm.xml</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <value>
    hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
    hibernate.show_sql=true
    hibernate.hbm2ddl.auto=update
   </value>
  </property>
 </bean>
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>
</beans>

需要注意的问题:
1: 导入jar包的时候,记得dom4j和xpath的支持jar包一起导入,否则会报找不到类异常;
2: 配置文件中不能存在乱 字符,否则会出现;java.lang.RuntimeException: org.dom4j.DocumentException: Error on line 1 of 
document file:///H:/Program/MyDay1/src/persistence.xml : Content is not allowed in 
prolog. Nested exception: Content is not allowed in prolog.问题;
3: 设置名称空间集合时即nsMap.put(key,value);key可以设置为任何值,value需为一个合法并存在的uri;
同时key前后必须一 ;
4: 使用junit测试时,就不能使用类装载器的方式获取一个流,给SAXReader解析获取Document文档;
温馨提示:
对xml文件的书写,最好使用子元 替代属性;
xpath文档和dom4j文档很有用;

 
阅读(38)|评论(0)
推荐 转载

历史上的今天

最近读者

热度

在LOFTER的更多文章

评论

 
\r\n

首先以spring的配置文件applicationContext.xml为例:

\r\n

 


\r\n
 package cn.itcast.dom4j;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
imp
', blogTag:'dom4j,xpath',blogUrl:'blog/static/21727620920135271142819', isPublished:1,istop:false, type:0, modifyTime:1372345809385,publishTime:1372345809313,permalink:'blog/static/21727620920135271142819', commentCount:0,mainCommentCount:0, recommendCount:0, bsrk:-100, publisherId:0,recomBlogHome:false, currentRecomBlog:false, attachmentsFileIds:[],vote:{}, groupInfo:{}, friendstatus:'none',followstatus:'unFollow', pubSucc:'', visitorProvince:'',visitorCity:'', visitorNewUser:false, postAddInfo:{}, mset:'000',mcon:'', srk:-100, remindgoodnightblog:false, isBlackVisitor:false,isShowYodaoAd:false,hostIntro:'JAVA软件工程师,有扎实的Java基础,熟悉JavaEE技术,对框架的底层原理熟悉,学习能力强。',hmcon:'0', selfRecomBlogCount:'0', lofter_single:'' }
{ifx.visitorName==visitor.userName} ${x.visitorNickname|escape} {else}${x.visitorNickname|escape} {/if}
{if x.moveFrom=='wap'}   {elseifx.moveFrom=='iphone'}   {elseifx.moveFrom=='android'}   {elseifx.moveFrom=='mobile'}   {/if}${fn(x.visitorNickname,8)|escape}
{/if} {/list}
${a.selfIntro|escape}{ifgreat260}${suplement}{/if}
 
{/if}
0 0