加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

当xml中存在命名空间,三种处理办…

发布时间:2020-12-16 05:19:11 所属栏目:百科 来源:网络整理
导读:当你解析XML时,是否会因为命名空间的存在而不能得偿所愿呢? .net上的解决方法我就不多说了(.net有世界上最详细的开发文档。这是我最欣赏微软的地方) java方面,好多人推荐用 dom4j处理xml,我也就说说在 dom4j 上处理带命名空间的xml 先说前两个方法,是

当你解析XML时,是否会因为命名空间的存在而不能得偿所愿呢?
.net上的解决方法我就不多说了(.net有世界上最详细的开发文档。这是我最欣赏微软的地方)
java方面,好多人推荐用dom4j处理xml,我也就说说在dom4j上处理带命名空间的xml

先说前两个方法,是从网上看来的。(来自http://blog.csdn.net/anyoneking/)摘抄如下:
xml代码example:

<</SPAN>reportxmlns="http://www.eclipse.org/birt/2005/design"version="3.2.15"id="1">
<</SPAN>list-propertyname="cssStyleSheets">
<</SPAN>structure>
<</SPAN>propertyname="fileName">D:eport.css</</SPAN>property>
</</SPAN>structure>
</</SPAN>list-property>
</</SPAN>report>

第一个方案.设置你的xpath的命名空间setNamespaceURIs

public class TransferXML{
public static void main(String[]args)throwsException{
Mapmap
= new HashMap();
map.put(
" design " , " http://www.eclipse.org/birt/2005/design " );
SAXReadersaxReader
= new SAXReader();
Filefile
= new File( " D:test.xml " );
Documentdocument
= saxReader.read(file);
XPathx
= document.createXPath( " //design:list-property " );
x.setNamespaceURIs(map);
Listnodelist
= x.selectNodes(document);
System.
out .println(nodelist.size());
}
}

第二个解决方案:设置你的DocumentFactory()的命名空间 setXPathNamespaceURIs

public class TransferXML{
public static void main(String[]args)throwsException{
Mapmap
= new HashMap();
map.put(
" design " , " http://www.eclipse.org/birt/2005/design " );
SAXReadersaxReader
= new SAXReader();
Filefile
= new File( " D:test.xml " );
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
Documentdocument
= saxReader.read(file);
Listtmp
= 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)throwsException
SAXReadersaxReader
= new SAXReader();
Filefile
= new File( " D:test.xml " );
Documentdocument
= saxReader.read(file);
Listtmp
= document.selectNodes( " //*[local-name()='report'andnamespace-uri()='http://www.eclipse.org/birt/2005/design']/*[local-name()='list-property'] " );
System.
out .println(tmp.size()); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读