dom4j解析带命名空间的xml

本文介绍了在解析带有命名空间的XML文件时,如何通过设置命名空间URI、使用DocumentFactory设置命名空间和创建XPath表达式选取特定元素的方法。提供了解决XML解析中命名空间问题的实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们解析xml的时候,如果该xml没有带命名空间,那么很好解析,直接用dom4j的selectNodes(XPath表达式)既可以了。但是如果命名空间那么则会返回空。下面为大家介绍三种方法来解决:

第一种:

<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的命名空间setNamespaceURI

 

public class TransferXML {
    public static void main(String[] args) throws Exception\{
         Map map = new HashMap();
         SAXReader saxReader = new SAXReader();
         File file = new File("D:\test.xml");
         Document document = saxReader.read(file);
String xmlNameSpace=c.getRootElement().getNamespaceURI();//取得命名空间
map.put("design","http://www.eclipse.org/birt/2005/design");//设置xml的命名空间

         XPath x = document.createXPath("//design:list-property");//填写XPath表达式
         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");//填充map
         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");//用XPath选取节点
         System.out.println(tmp.size());
     }
}
详细请参考:http://blog.sina.com.cn/s/blog_4bf2e5550100sbb7.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值