package com.hutu.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.hutu.po.Clerk;
public class XmlReader {
public NodeList readXml() {
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
NodeList nodeList = null;
FileOutputStream fileOutputStream=null;
StringBuffer sBuffer=new StringBuffer("编号\t\t\t"+"姓名\t\t"+"性别\t\t"+"年龄\n");
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
Document document = builder.parse("clerk.xml");
Element rootElement = document.getDocumentElement();// 获取根节点
nodeList = rootElement.getChildNodes();// 获取根节点下的子节点
for (int i = 0; i < nodeList.getLength(); i++) {
Clerk clerk=new Clerk();//创建对象实例
Node node = nodeList.item(i);
if (node.getNodeType() == node.ELEMENT_NODE) {
// int idValue=Integer.parseInt(node.getAttributes().item(0).getNodeValue());//在不知道属性名字前提下,这样操作
int idValue = Integer.parseInt(node.getAttributes()
.getNamedItem("id").getNodeValue());// 在知道属性名字前提下,这样操作
clerk.setId(idValue);//给对象 赋值
NodeList childNodeList=node.getChildNodes();
for(int j=0;j<childNodeList.getLength();j++){
Node childNode=childNodeList.item(j);
if(childNode.getNodeName().equalsIgnoreCase("name")){
clerk.setName(childNode.getTextContent());
}else if(childNode.getNodeName().equalsIgnoreCase("sex")){
clerk.setSex(childNode.getTextContent());
}else if(childNode.getNodeName().equalsIgnoreCase("age")){
clerk.setAge(Integer.parseInt(childNode.getTextContent()));
}
}
// System.out.println(clerk.getId()+"\t"+clerk.getName()+"\t"+clerk.getSex()+"\t"+clerk.getAge());
fileOutputStream=new FileOutputStream(new File("info.txt"));
sBuffer.append(clerk.getId()+"\t\t"+clerk.getName()+"\t\t"+clerk.getSex()+"\t\t\t"+clerk.getAge()+"\n");
fileOutputStream.write(sBuffer.toString().getBytes());
fileOutputStream.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nodeList;
}
public static void main(String[] args) {
new XmlReader().readXml();
}
}