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: est.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: est.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: est.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();
- }
- }