读取数据
一、dom4j操作blob字段
1、从数据库中读
Document document =null;
formdata = new String(rs.getBytes(1), "UTF-8");
document = DocumentHelper.parseText(formdata);
二、读取文件
String path=Config.workPath+"cfg/FieldMap.xml";
InputStream is =new FileInputStream(new File(path));
SAXReader sax = new SAXReader();
Document xmlDoc = sax.read(is);
元素操作
1) 获取根节点
Element rootElt = doc.getRootElement();
2)获取根节点下的子节点
Iterator iter = rootElt.elementIterator("head");
3)遍历head节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
// 拿到head节点下的子节点title值
String title = recordEle.elementTextTrim("title");
或者title=recordEle.attributeValue("title");
}
4)得到同级的标签值.
例如: <elements RPT_ISLOCK="0" RPT_INDEX="15" RPT_NAME="Button_15"/>
得到 itemEle.attribute("RPT_INDEX").getValue()
element.attributeValue("RPT_UPDATESTIME")
5)将Element转化成List
List list = element.attributes();
6)得到子集标签值
<elements>
<a>aaaa</a>
<b>bbbb</a>
</
<elements>
Iterator data = root.elementIterator("elements
");
while (data.hasNext()) {
Element item = (Element) data.next();
String a= item.element("a").getText();
String b= item.element("a").getText();
}
=========dom4j创建xml==============
1\创建xml
*//** 建立document对象 *//*
Document document = DocumentHelper.createDocument();
*//** 建立XML文档的根tables *//*
Element tables=document.addElement("tables");
*//** 加入一行注释 *//*
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
*//** 加入第一个book节点 *//*
Element bookElement = booksElement.addElement("book");
*//** 加入show属性内容 *//*
bookElement.addAttribute("show","yes");
*//** 加入title节点 *//*
Element titleElement = bookElement.addElement("title");
*//** 为title设置内容 *//*
titleElement.setText("Dom4j Tutorials");
try{
*//** 将document中的内容写入文件中 *//*
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
*//** 执行成功,需返回1 *//*
returnValue = 1;
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
/**
* 保存xml文件
* @param document
* @param encoding
* @param path
* @throws IOException
*/
public static void saveDocument(Document document,String encoding, String path ) throws IOException {
XMLWriter writer = null;
File pf = new File(path);
if (!pf.exists()) {
pf.mkdirs();
}
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
FileOutputStream fos = new FileOutputStream(new File(path));
writer = new XMLWriter(fos, format);
writer.write(document);
} catch (IOException i) {
System.out.println("写文件失败");
i.printStackTrace();
} finally {
writer.close();
}
}