---
title: "当xml中存在命名空间，三种处理办法（dom4j） "
author: "ssuhvs"
date: "2010-07-15T11:08:39Z"
tags: []
categories: ["企业架构"]
slug: "xml-dom4j"
draft: false
lastmod: "2010-07-15T11:08:39Z"
id: 713245
url: "https://ssuhvs.iteye.com/blog/713245"
---

当xml中存在命名空间，三种处理办法（dom4j） 
Posted on 2008-04-02 11:56 暴走的猪 阅读(1184) 评论(0) 编辑 收藏 所属分类: JAVA  
当你解析XML时，是否会因为命名空间的存在而不能得偿所愿呢？
.net上的解决方法我就不多说了（.net有世界上最详细的开发文档。这是我最欣赏微软的地方）
java方面，好多人推荐用dom4j处理xml，我也就说说在dom4j上处理带命名空间的xml

先说前两个方法，是从网上看来的。（来自http://blog.csdn.net/anyoneking/）摘抄如下：
xml代码example:


<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.css</property>
        </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("//*/* ");
        System.out.println(tmp.size());
    }
}