XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。
XPath 使用路径表达式来选取 XML 文档中的节点或节点集。节点是通过沿着路径 (path) 或者步 (steps) 来选取的。
w3school XPath教程
Dom4J学习笔记
例子1:
D: eport.css
第一个方案.设置你的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:
r1app.nvts.co 美国东1 US-East1 r2app.nvts.co 日本1 JP-1 r3app.nvts.co 欧洲1 EU-1
/**
* 初始化CameraServerAddress,从xml配置文件初始化
*/
@SuppressWarnings("unchecked")
public void initCameraServerAddresses(){
try {
Map uris = new HashMap();
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 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(自己例子):
http://localhost:8888/ws1?wsdl http://localhost:8888/ws2?wsdl http://localhost:8888/ws3?wsdl http://localhost:8889/ws4?wsdl http://10.204.104.87:8888/ESB_YS_YS_InquiryMachineInfoSrv/ESBYSYSInquiryMachineInfoSrv?wsdl
/**
* 添加或更新单个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 es = findWebserviceElements(wi, root);
if(es.size() > 0){
// 删除doc中的元素
for(Element e : es){
root.remove(e);
}
// 删除集合中的元素
Iterator 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 findWebserviceElements(WebserviceNode wi, Element root) {
Map ns = new HashMap();
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 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();
}
}
。。