DOM4J处理XML带有命名空间的四种方法

当你解析XML时,是否会因为命名空间的存在而不能得偿所愿呢?
.net上的解决方法我就不多说了(.net有世界上最详细的开发文档。这是我最欣赏微软的地方)
java方面,好多人推荐用dom4j处理xml,我也就说说在dom4j上处理带命名空间的xml
先说前两个方法,是从网上看来的。(来自http://blog.csdn.net/anyoneking/)摘抄如下:
xml代码example:

再说前三种方法,也是从网上看来的。http://www.cnblogs.com/patrickchen/articles/1188920.html

<report xmlns="http://www.eclipse.org/birt/2005/design" version="3.2.15" id="1"> <list-property name="cssStyleSheets"> <structure> <property name="fileName">D: eport.cssproperty> structure> list-property> report>

第一个方案.设置你的xpath的命名空间setNamespaceURIs
public class TransferXML {
public static void main(String[] args) throws Exception {
Map map = new HashMap();
map.put("design", "http://www.eclipse.org/birt/2005/design");
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
Document document = saxReader.read(file);
XPath x = document.createXPath("//design:list-property");
x.setNamespaceURIs(map);
List nodelist = x.selectNodes(document);
System.out.println(nodelist.size());
}
}


第二个解决方案:设置你的DocumentFactory()的命名空间 setXPathNamespaceURIs
public class TransferXML {
public static void main(String[] args) throws Exception {
Map map = new HashMap();
map.put("design", "http://www.eclipse.org/birt/2005/design");
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
Document document = saxReader.read(file);
List tmp = document.selectNodes("//design:list-property");
System.out.println(tmp.size());
}
}


第三种方法:本人用的,最笨也是最通用的方法,就是不使用开发环境给你提供的一系列对象,而是用XPath语法中自带的local-name() 和 namespace-uri() 指定你要使用的节点名和命名空间。
当你遇到使用xslt来样式化xml时,就知道这个笨方法的好处了:
public class TransferXML {
public static void main(String[] args) throws Exception {
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
Document document = saxReader.read(file);
List tmp = document.selectNodes("//*[local-name()='report' and namespace-uri()='http://www.eclipse.org/birt/2005/design']/* [local-name()='list-property']");
System.out.println(tmp.size());
}
}


第四种方法: 本人曾经和别人探讨时用到的,当只需要一个元素时,也可以不用设置命名空间。用element的element方法取一个子元素或elementIterator方法取多个元素。当只要获取属性时,可以用document的selectNodes方法。
public class TransferXML {
public static void main(String[] args) throws Exception {
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
Document document = saxReader.read(file);
Element root = document.getRootElement();
Element ele = root.element("report");
System.out.println(ele.getName());
List list = document.selectNodes("//@name");
System.out.println(list.size());
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值