第一步 生成xml文件
下载jar包 jdom.jar
需要导入的包
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import weibo4j.Mentions;
import weibo4j.examples.timeline.GetMentions;
// 生成XML
public void CreateXml() throws FileNotFoundException, IOException {
// 创建根节点
Element root = new Element("XML");
// 根节点添加到文档中
Document doc = new Document(root);
// 调用数据来源方法
ResultSet rs=dd.getAll();//调用业务层方法
// 遍历实体
int num = 1;
while(rs.next() {
// 创建节点user
Element eluser = new Element("eleOne");
// 给user节点添加属性
eluser.setAttribute("id", "" + num);
// 给user节点添加子节点并赋值
eluser.addContent(new Element("Name").setText(rs.getString("name") + ""));
eluser.addContent(new Element("Content").setText(rs.getString("contend")
+ ""));
eluser.addContent(new Element("Time").setText(rs.getString("time") + ""));
// 给父节点list添加user子节点
root.addContent(eluser);
num++;
}
// 输出user.xml文件
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.output(doc, new FileOutputStream("newxmlfile.xml"));
}
第二步
读取xml文件
// 遍历XML
public void parseXml(File xmlFile) {
SAXBuilder sax = new SAXBuilder();
try {
Document xmlDom = sax.build(xmlFile);
Element root = xmlDom.getRootElement();
System.out.println("根元素是:" + root.getName());
List childList = root.getChildren();
Iterator listIt = childList.iterator();
while (listIt.hasNext()) {
Element element = (Element) listIt.next();
System.out.println("第一子节点是:" + element.getName());
}
System.out.println("\n\n\n\n");
for(int i=0;i<childList.size();i++){
Element firstChild = (Element) childList.get(i);
List attrList = firstChild.getAttributes();
List sonList = firstChild.getChildren();
Iterator sonIt = sonList.iterator();
int num=0;
while (sonIt.hasNext()) {
Element temp = (Element) sonIt.next();
System.out.println("属性" + temp.getName() + "的值是:"
+ temp.getValue());
num++;
if(num==7){
num=0;
System.out.println("\n\n");
}
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
下载jar包
需要导入的包
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import weibo4j.Mentions;
import weibo4j.examples.timeline.GetMentions;
第二步
读取xml文件
// 遍历XML