使用dom4j和xpath
程序员文章站
2022-05-28 21:03:21
...
使用dom4j和XPath
配置开发包
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar(XPath必备)
取某一节点
Element root = (Element) document.selectSingleNode("//root");
取某一节点的属性
Attribute attribute = (Attribute) document.selectSingleNode("//root/cell/@value");
使用经验
我们在做系统间交互时,通常通过自定义的xml文件进行数据交换。例如:系统A需要向系统B传输一个xml字串的条件如下:
<?xml version="1.0" encoding="gb2312"?> <root systemid="Darenkou" userid="admin" default="DA" icon="0000"> <cell value=""/> </root>
系
统A只需填充cell节点的value属性值,我的建议是将这段xml写成本地文件,每次传输时首先读取xml文件,再置cell节点的
value属性值,然后将xml对象转变成字串传给系统B。这样的优点是:一般systemid="Darenkou" userid="admin"
default="DA" icon="0000" 是传输参数,当有所变动时只需修改本地文件即可。
详细例程
test.xml
<?xml version="1.0" encoding="gb2312"?>;
<root id="TK12" name="管理员" value=""/>;
XmlTest.java
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlTest {
public static String generateXml(HashMap map) {
String strXml = null;
if (map != null) {
SAXReader reader = new SAXReader();
Document document = null;
try {
document = reader.read(new File("D:/test.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
Element root = (Element) document.selectSingleNode("//root");
root.attribute("value").setValue("分布");
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = (String) map.get(key);
Element element = root.addElement("cell").addAttribute("value",
key);
element.addElement("element").addAttribute("type", "数值")
.addAttribute("name", "人数").addText(value);
}
strXml = encodeXml(document, "gb2312");
}
return strXml;
}
private static String encodeXml(Document document, String aEncode) {
// 进行编码转换
StringWriter sw = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(aEncode);
try {
XMLWriter writer = new XMLWriter(format);
writer.setWriter(sw);
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sw.toString();
}
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("上海", "200");
map.put("北京", "300");
map.put("天津", "300");
System.out.println(generateXml(map));
}
}
上一篇: 浙江茶叶,带你领略浙江茶文化