关于dom4j在解析拥有命名空间xmlns时,无法解析的问题

在一个birt开发的项目中,遇到了解析birt生成的xml报表文件的情况,于是决定用dom4j来解决.[需要下载dom4j.jar,jaxen-1.1-beta-10.jar]这两个类库.一开始还忘记了加入jaxen造成了错误.
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>
我按照dom4j一般的解析方式进行了编码:
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("//list-property");
        System.out.println(tmp.size());
    }
}
结果输出为0.并不是我预想中的1.
而且代码比较简单,应该不存在问题.然后,我又找了一个不同的xml文件,结果能够成功找到node.
用比较工具对2个xml文件进行了compare.结果只是存在xmlns的区别.一个有一个没有.faint......
查找了相关资料,网上,或者api等等.考虑出了2个解决方案.其中第一个为从网上搜取到的,姑且写在这里,只是个参考(千万别告我,怕怕的说).
第一个方案.
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());
    }
}
第二个解决方案:
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());
    }
}
相较而言,我还是比较倾向于第二种方法.
如果你们有更好的方法,可以跟我留下.仅供参考.
--------------------- 
作者:anyoneking 
来源:CSDN 
原文:https://blog.csdn.net/anyoneking/article/details/2077074 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/xingqibaing/article/details/91881270