dom4j处理带命名空间的XML-使用XPath(转)
XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。
XPath 使用路径表达式来选取 XML 文档中的节点或节点集。节点是通过沿着路径 (path) 或者步 (steps) 来选取的。
例子1:
- <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
XPath x = document.createXPath("//design:list-property");
x.setNamespaceURIs(map);
x.selectNodes(document);
- 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);
- Map map = new HashMap();
- map.put("design","http://www.eclipse.org/birt/2005/design");
- XPath x = document.createXPath("//design:list-property");
- x.setNamespaceURIs(map);
- List nodelist = x.selectNodes(document);
- System.out.println(nodelist.size());
- }
- }
第二个解决方案:设置你的DocumentFactory()的命名空间 setXPathNamespaceURIs
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
Document document = saxReader.read(file);
document.selectNodes("//design:list-property");
- 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时,就知道这个笨方法的好处了:
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']");
- 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());
- }
- }
例子2:
- <?xml version="1.0" encoding="UTF-8"?>
- <addresses xmlns="http://www.example.org/cameraServerAddress" >
- <address>
- <db>r1app.nvts.co</db>
- <zh>美国东1</zh>
- <en>US-East1</en>
- </address>
- <address>
- <db>r2app.nvts.co</db>
- <zh>日本1</zh>
- <en>JP-1</en>
- </address>
- <address>
- <db>r3app.nvts.co</db>
- <zh>欧洲1</zh>
- <en>EU-1</en>
- </address>
- </addresses>
- /**
- * 初始化CameraServerAddress,从xml配置文件初始化
- */
- @SuppressWarnings("unchecked")
- public void initCameraServerAddresses(){
- try {
- Map<String,String> uris = new HashMap<String, String>();
- uris.put("cameraServerAddress" , "http://www.example.org/cameraServerAddress");
- SAXReader reader = new SAXReader();
- Document root = reader.read(this.getClass().getClassLoader().getResourceAsStream("cameraServerAddresses.xml"));
- XPath xpath = root.createXPath("//cameraServerAddress:address"); //创建XPath
- xpath.setNamespaceURIs(uris); //加入NameSpace
- List<DefaultElement> nodes = xpath.selectNodes(root); //执行搜索
- for (DefaultElement de : nodes) {
- de.add(new Namespace("cameraServerAddress", "http://www.example.org/cameraServerAddress")); //这里也要再次加入NameSpace
- Node db = de.selectSingleNode("cameraServerAddress:db");
- Node zh = de.selectSingleNode("cameraServerAddress:zh");
- Node en = de.selectSingleNode("cameraServerAddress:en");
- NVContext.cameraServerAddresses.add(new CameraServerAddress(
- db.getText(), zh.getText(), en.getText()));
- }
- } catch (Exception e) {
- log.error("初始化CameraServerAddress失败");
- e.printStackTrace();
- }
- }
例子3(自己例子):
- <?xml version="1.0" encoding="UTF-8"?>
- <webservices xmlns="http://ws.test.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="webservices.xsd">
- <webservice wsname="ws1" wsversion="">
- <wsdlurl>http://localhost:8888/ws1?wsdl</wsdlurl>
- </webservice>
- <webservice wsname="ws2">
- <wsdlurl>http://localhost:8888/ws2?wsdl</wsdlurl>
- </webservice>
- <webservice wsname="ws3" wsversion="v1">
- <wsdlurl>http://localhost:8888/ws3?wsdl</wsdlurl>
- </webservice>
- <webservice wsname="srv4">
- <wsdlurl>http://localhost:8889/ws4?wsdl</wsdlurl>
- </webservice>
- <webservice wsname="ESB_YS_YS_InquiryMachineInfoSrv">
- <wsdlurl>http://10.204.104.87:8888/ESB_YS_YS_InquiryMachineInfoSrv/ESBYSYSInquiryMachineInfoSrv?wsdl</wsdlurl>
- </webservice>
- </webservices>
- /**
- * 添加或更新单个webservice子节点
- * @param wi 封装的服务信息
- */
- public synchronized void addOrUpdate(WebserviceNode wi) {
- if(doc != null){
- Element root = doc.getRootElement();
- addOrUpdateWebservice(wi, root);
- save();
- }
- }
- /**
- * 在指定的节点上添加webservice子节点
- *
- * @param wi 封装的服务信息
- * @param root root节点
- */
- private void addOrUpdateWebservice(WebserviceNode wi, Element root) {
- removeWebservices(wi, root);
- addOrUpdateWebserviceElement(wi, root);
- wis.add(wi);
- }
- private void removeWebservices(WebserviceNode wi, Element root) {
- List<Element> es = findWebserviceElements(wi, root);
- if(es.size() > 0){
- // 删除doc中的元素
- for(Element e : es){
- root.remove(e);
- }
- // 删除集合中的元素
- Iterator<WebserviceNode> wiIterator = wis.iterator();
- while(wiIterator.hasNext()){
- WebserviceNode i = wiIterator.next();
- if(i.equals(wi)){
- wiIterator.remove();
- }
- }
- }
- }
查找满足条件的子节点:
- /**
- * 查找匹配的webservice元素
- *
- * @param wi
- * @param root
- * @return
- */
- @SuppressWarnings("unchecked")
- private List<Element> findWebserviceElements(WebserviceNode wi, Element root) {
- Map<String, String> ns = new HashMap<String, String>();
- ns.put("vis", "http://ws.test.com");
- String xpath = "/vis:webservices/vis:webservice[@wsname='"+ wi.getWsName() + "'" + (wi.hasVersionInfo() ? " and @wsversion='" + wi.getWsVersion() + "'" : " and (not(@wsversion) or normalize-space(@wsversion)='')") + "]";
- XPath x = root.createXPath(xpath);
- x.setNamespaceURIs(ns);
- //System.out.println(xpath);
- List<Element> es = x.selectNodes(root);
- return es;
- }
- /**
- * 在指定的节点上添加webservice子节点(xml document)
- *
- * @param wi
- * @param root
- */
- private void addOrUpdateWebserviceElement(WebserviceNode wi, Element root) {
- Element ws = root.addElement("webservice");
- ws.addAttribute("wsname", wi.getWsName());
- if(wi.hasVersionInfo()){
- ws.addAttribute("wsversion", wi.getWsVersion());
- }
- ws.addElement("wsdlurl").setText(wi.getWsdlUrl());
- }
保存XML文件:
- /**
- * 保存至硬盘
- */
- private void save() {
- // 将document保存至硬盘
- OutputFormat format = OutputFormat.createPrettyPrint();
- try {
- XMLWriter writer = new XMLWriter(new FileWriter(PATH), format);
- writer.write(doc);
- writer.close();
- } catch (IOException e) {
- System.err.println("Persist '" + PATH + "' is Failed...");
- e.printStackTrace();
- }
- }
dom4j处理带命名空间的XML-使用XPath(转)的更多相关文章
- dom4j解析带命名空间的xml文件
文件内容如下 <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=& ...
- 带命名空间的XML的dom4j应用<转>
Element root = document.getRootElement(); List recordenvlist = document.selectNodes("//gm ...
- C#读取带命名空间的xml,xaml文件的解决方案
使用C#读取xml文件有三种常用的方式: 1.xmlDocument 2.XmlTextReader 3.Linq To Xml 但是这些方式在读写有些带命名空间的xml时就不知道怎么办了(例如把xa ...
- 由“Jasperrpeorts 4.1.2升级到5.1.2对flex项目的解析”到AS3 带命名空间的XML的操作
原文同步至:http://www.waylau.com/from-jasperrpeorts-4-1-2-upgraded-to-5-1-2-parsing-of-flex-projects-to-t ...
- C#读取带命名空间的xml
首先带有命名空间的xml读取可以使用Xml.Linq,也可以使用xpath,本文将采用xpath的方式解析. 原文参考了:https://www.cnblogs.com/duanjt/p/544054 ...
- Linq to xml 操作带命名空间的xml
昨天需要操作用代码操作csproj文件,实现不同vs版本的切换. 在用XElement读取了csproj文件以后怎么也获取不到想要的对象. 反反复复试验了好多次都不得要领:先看下csproj文件的内容 ...
- XML记一次带命名空间的xml读取
public static void ReadXML(string xmlUrl) { //判断文件是否存在 if (!File.Exists(xmlUrl)) { Console.WriteLine ...
- linq检索带命名空间的xml
XElement el = XElement.Load(fil); XNamespace ns = "http://schemas.microsoft.com/ado/2009/11/edm ...
- Linq to Xml读取复杂xml(带命名空间)
前言:xml的操作方式有多种,但要论使用频繁程度,博主用得最多的还是Linq to xml的方式,觉得它使用起来很方便,就用那么几个方法就能完成简单xml的读写.之前做的一个项目有一个很变态的需求:C ...
随机推荐
- Error: Cannot find module '@babel/core'
报错如下 产生原因 babel-loader和babel-core版本不对应所产生的, babel-loader 8.x对应babel-core 7.x babel-loader 7.x对应babel ...
- 从别人git下载项目下来然后运行
1点击clone or download 2.自由选择 3.拉到你想放的位置,我是放到桌面上的 4. cmd 打开,进入你 的下载到桌面的项目 5. # install dependencies n ...
- delphi 还原窗口
1.格局还原procedure TFrmStyleProp.btnNewClick(Sender: TObject); //声明var iniFile : TIniFile; idx : intege ...
- OrCAD(2) -- 编辑原理图库时的复制与粘贴
大家都知道,OrCAD元器件的管脚编辑是基于Excel的,但是在编辑原理图库的管脚的时候,大家应该都有体会'ctrl+c' 和 'ctrl+v' 的命令是不能用的. 这是因为该两个命令在OrCAD中都 ...
- C++ 俄罗斯方块
#include <iostream> #include <string.h> #include <stdlib.h> #include <time.h> ...
- hadoop新增新数据节点和退役数据节点
新增数据节点 0. 需求随着公司业务的增长,数据量越来越大,原有的数据节点的容量已经不能满足存储数据的需求,需要在原有集群基础上动态添加新的数据节点.1. 环境准备 (1)在hadoop03主机上再克 ...
- 1636: Pascal山脉
1636: Pascal山脉 时间限制: 1 Sec 内存限制: 128 MB提交: 51 解决: 15[提交][状态][讨论版] 题目描述 小卡卡顺着老者所指的方向,来到了Pascal神峰的顶峰 ...
- 在VC中使用WebBrowser控件的两方法
ClassWizard方式: 1.创建包装类:View->ClassWizard->Add Class->Form a Type Library->C:/winnt/syste ...
- tomcat JAVA_OPTS设置
原文地址:https://blog.csdn.net/bamboo_cqh/article/details/72820700 AVA_OPTS ,顾名思义,是用来设置JVM相关运行参数的变量. JVM ...
- SSL和TLS漏洞验证
工具下载:git clone https://github.com/drwetter/testssl.sh.git 实验环境:192.168.1.22(bee-box v1.6) 192.168.1. ...