Dom4j and XPath

很多东西长时间不用, 有些生疏了, 从网上整理了些资料, 丢在这方便以后找.

先上代码:

<?xml version="1.0" encoding="GBK"?>
<resin xmlns="http://caucho.com/ns/resin" xmlns:resin="http://caucho.com/ns/resin/core">
<server>
<http server-id="" host="*" port="9088"/>
</server>
</resin>




package com.abc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* 读写Resin.conf助手类
*/
public class ResinConfHelper {
private static final String HTTP_SERVER_NODE = "//resin/server/http";
private static final String DEFAULT_NS = "http://caucho.com/ns/resin";
private static final String RESIN_NS = "http://caucho.com/ns/resin/core";
private static final String DEFAULT_NS_KEY = "default";
private static final String RESIN_NS_KEY = "resin";
private static final String DEFAULT_ENCODING = "GBK";
private String resinConfFilePath;
private Document doc;
public ResinConfHelper(String resinConfFilePath) {
this.resinConfFilePath = resinConfFilePath;
}

public String getHttpPort() {
return getAttributeValue(HTTP_SERVER_NODE, "port");
}

public void setHttpPort(String port) {
setAttributeValue(HTTP_SERVER_NODE, "port", port);
}

public void setHttpPort(int port) {
setAttributeValue(HTTP_SERVER_NODE, "port", String.valueOf(port));
}

public void init() throws DocumentException {
Map<String, String> namespaceURIs = new HashMap<String, String>();
namespaceURIs.put(DEFAULT_NS_KEY, DEFAULT_NS);
namespaceURIs.put(RESIN_NS_KEY, RESIN_NS);

DocumentFactory docFactory = new DocumentFactory();
docFactory.setXPathNamespaceURIs(namespaceURIs);

SAXReader reader = new SAXReader(docFactory);
File resinConfFile = new File(resinConfFilePath);
doc = reader.read(resinConfFile);
}

public void save() throws IOException {
XMLWriter writer = null;
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(DEFAULT_ENCODING); // 指定XML编码
writer = new XMLWriter(new FileWriter(resinConfFilePath), format);
writer.write(doc);
}
catch (Exception e) {
System.err.println(e);
}
finally {
IoUtils.closeQuietly(writer);
}
}

public String getTextValue(String xPath) {
return getElementByXPath(xPath).getTextTrim();
}

public String getAttributeValue(String xPath, String attrName) {
return getElementByXPath(xPath).attributeValue(attrName);
}

private Element setAttributeValue(String xPath, String attrName, String attrValue) {
return getElementByXPath(xPath).addAttribute(attrName, attrValue);
}

private Element getElementByXPath(String xPath) {
return (Element) doc.selectSingleNode(getXPathWithNSByDefualt(xPath));
}

private static String getXPathWithNSByDefualt(String xpath) {
xpath = xpath.replaceAll("/(\\w)", "/" + "default:$1"); // replace start with "/"
xpath = xpath.replaceAll("^(\\w)", "default:$1"); // replace start with word
return xpath;
}

public static void main(String[] args) throws Exception {

String file = "resin.conf";
ResinConfHelper helper = new ResinConfHelper(file);
helper.init();
System.out.println(helper.getHttpPort());

helper.setHttpPort(9088);
helper.save();
}

}



---------------------------------------------------------------------
要点:
如果XML带有命名空间, 直接以原来熟悉的XPath语法是得不到相应的节点的.
必须在解析XML之前, 设置相应的命名空间, 并在获取节点前对XPat做相应的处理(加上对应的命名空间标识).

---------------------------------------------------------------------
xpath语法

1、选取节点

XPath 使用路径表达式在 XML 文档中选取节点,节点是沿着路径或者 step 来选取的。
常见的路径表达式:
[table]
|表达式 | 描述|
|nodename|选取当前节点的所有子节点|
|/ |从根节点选取|
|//|从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置|
|.|选取当前节点|
|..|选取当前节点的父节点|
|@|选取属性|
[/table]

实例
[table]
|路径表达式|结果|
|bookstore|选取 bookstore 元素的所有子节点|
|/bookstore|选取根元素 bookstore|
|bookstore/book|选取bookstore 下名字为 book的所有子元素。|
|//book|选取所有 book 子元素,而不管它们在文档中的位置。|
|bookstore//book|选取bookstore 下名字为 book的所有后代元素,而不管它们位于 bookstore 之下的什么位置。|
|//@lang|选取所有名为 lang 的属性。|
[/table]

2、谓语(Predicates)
谓语用来查找某个特定的节点或者包含某个指定的值的节点。
谓语被嵌在方括号中。
实例
常见的谓语的一些路径表达式:
[table]
|路径表达式|结果|
|/bookstore/book[1]|选取属于 bookstore 子元素的第一个 book 元素。|
|/bookstore/book[last()]|选取属于 bookstore 子元素的最后一个 book 元素。|
|/bookstore/book[last()-1]|选取属于 bookstore 子元素的倒数第二个 book 元素。|
|/bookstore/book[position()<3]|最前面的两个属于 bookstore 元素的子元素的 book 元素。|
|//title[@lang]|选取所有拥有名为 lang 的属性的 title 元素。|
|//title[@lang='eng']|选取所有 title 元素,要求这些元素拥有值为 eng 的 lang 属性。|
|/bookstore/book[price>35.00]|选取所有 bookstore 元素的 book 元素,要求book元素的子元素 price 元素的值须大于 35.00。|
|/bookstore/book[price>35.00]/title|选取所有 bookstore 元素中的 book 元素的 title 元素,要求book元素的子元素 price 元素的值须大于 35.00|
[/table]

3、选取未知节点

XPath 通配符可用来选取未知的 XML 元素。
[table]
|通配符|描述|
|*|匹配任何元素节点|
|@*|匹配任何属性节点|
|node()|匹配任何类型的节点|
[/table]
实例
[table]
|路径表达式|结果|
|/bookstore/*|选取 bookstore 元素的所有子节点|
|//*|选取文档中的所有元素|
|//title[@*]|选取所有带有属性的 title 元素。|
[/table]

4、选取若干路径
通过在路径表达式中使用“|”运算符,您可以选取若干个路径。
实例 (将"|"替换为"|")
[table]
|路径表达式|结果|
|//book/title | //book/price|选取所有 book 元素的 title 和 price 元素。|
|//title | //price|选取所有文档中的 title 和 price 元素。|
|/bookstore/book/title|//price|选取所有属于 bookstore 元素的 book 元素的 title 元素,以及文档中所有的 price 元素。|
[/table]

5、XPath 轴
轴可定义某个相对于当前节点的节点集
[table]
|轴名称|结果|
|ancestor|选取当前节点的所有先辈(父、祖父等)|
|ancestor-or-self|选取当前节点的所有先辈(父、祖父等)以及当前节点本身|
|attribute|选取当前节点的所有属性|
|child|选取当前节点的所有子元素。|
|descendant|选取当前节点的所有后代元素(子、孙等)。|
|descendant-or-self|选取当前节点的所有后代元素(子、孙等)以及当前节点本身。|
|following|选取文档中当前节点的结束标签之后的所有节点。|
|namespace|选取当前节点的所有命名空间节点|
|parent|选取当前节点的父节点。|
|preceding|选取文档中当前节点的开始标签之前的所有节点。|
|preceding-sibling|选取当前节点之前的所有同级节点。|
|self|选取当前节点。|
[/table]

6、路径

Ø 位置路径表达式
位置路径可以是绝对的,也可以是相对的。
绝对路径起始于正斜杠( / ),而相对路径不会这样。在两种情况中,位置路径均包括一个或多个步,每个步均被斜杠分割:
Ø 绝对位置路径: /step/step/...
Ø 相对位置路径: step/step/...
每个步均根据当前节点集之中的节点来进行计算。
Ø 步(step)包括:
轴(axis):定义所选节点与当前节点之间的树关系
节点测试(node-test):识别某个轴内部的节点
零个或者更多谓语(predicate):更深入地提炼所选的节点集
步的语法:轴名称::节点测试[谓语]
实例

实例
[table]
|例子|结果|
|child::book|选取所有属于当前节点的子元素的 book 节点|
|attribute::lang|选取当前节点的 lang 属性|
|child::*|选取当前节点的所有子元素|
|attribute::*|选取当前节点的所有属性|
|child::text()|选取当前节点的所有文本子节点|
|child::node()|选取当前节点的所有子节点|
|descendant::book|选取当前节点的所有 book 后代|
|ancestor::book|选择当前节点的所有 book 先辈|
|ancestor-or-self::book|选取当前节点的所有book先辈以及当前节点(假如此节点是book节点的话)|
|child::*/child::price|选取当前节点的所有 price 孙。|
[/table]

7、XPath 运算符
[table]
|运算符|描述|实例|返回值|
|||计算两个节点集|//book | //cd|返回所有带有 book 和 ck 元素的节点集|
|+|加法|6 + 4|10|
|-|减法|6 - 4|2|
|*|乘法|6 * 4|24|
|div|除法|8 div 4|2|
|=|等于|price=9.80|如果 price 是 9.80,则返回 true。如果 price 是 9.90,则返回 fasle。|
|!=|不等于|price!=9.80|如果 price 是 9.90,则返回 true。如果 price 是 9.80,则返回 fasle。|
|< |小于|price<9.80|如果 price 是 9.00,则返回 true。如果 price 是 9.90,则返回 fasle。|
|<=|小于或等于|price<=9.80|如果 price 是 9.00,则返回 true。如果 price 是 9.90,则返回 fasle。|
|> |大于|price>9.80|如果 price 是 9.90,则返回 true。如果 price 是 9.80,则返回 fasle。|
|>=|大于或等于|price>=9.80|如果 price 是 9.90,则返回 true。如果 price 是 9.70,则返回 fasle。|
|or|或|price=9.80 or price=9.70|如果 price 是 9.80,则返回 true。如果 price 是 9.50,则返回 fasle。|
|and|与|price>9.00 and price<9.90|如果 price 是 9.80,则返回 true。如果 price 是 8.50,则返回 fasle。|
|mod|计算除法的余数|5 mod 2|1|
[/table]

参考:
[url]http://blog.csdn.net/chifengxin/article/details/7035885[/url]
[url]http://www.blogjava.net/eclipser/articles/228367.html[/url]
[url]http://blog.csdn.net/blueman2012/article/details/6684177[/url]
[url]http://selvemen.iteye.com/blog/1139990[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值