package cn.gdpe.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class XmlReader {
/**
* @param args
* @throws DocumentException
*
* 读取xml文档
*/
public static void main(String[] args) throws Exception {
new XmlReader().xmlTest();
// List<Person> persons=new XmlReader().toPerson();
// for(Person p:persons){
// System.out.println(p.toString());
// }
}
public void xmlTest(){
try {
SAXReader sr=new SAXReader();
Document dc=sr.read("src/xml1.xml");
StringBuffer s=new StringBuffer();
Element root=dc.getRootElement();
getChildNode(root,s);
System.out.println(s.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void getChildNode(Element ele,StringBuffer sb){
sb.append("<"+ele.getName()+"");
List<Attribute> attrs=ele.attributes();
if(attrs!=null){
for(Attribute attr:attrs){
sb.append(" "+attr.getName()+"=\""+attr.getValue()+"\"");
}
}sb.append(">");
Iterator<Node> it=ele.nodeIterator();
while(it.hasNext()){
Node node=it.next();
if(node.getNodeTypeName()=="Element"){
Element e=(Element)node;
getChildNode(e,sb);
}else{
sb.append(node.getText());
}
}
sb.append("</"+ele.getName()+">");
}
public void addChildNode(Element ele) throws IOException{
ele.addElement("person");
File file=new File("src/xml1.xml");
InputStream is=new FileInputStream(file);
int len=0;
byte[] b=new byte[1024];
while((len=is.read(b))!=-1){
System.out.println(new String(b,0,len));
}
}
public List<Person> toPerson(){
List<Person> persons=new ArrayList<Person>();
try {
SAXReader sr=new SAXReader();
Document dc = sr.read("src/xml1.xml");
Element root=dc.getRootElement();
List<Element> eles=root.elements();
for(Element e:eles){
List<Element> es=e.elements();
Person person=new Person();
for(Element ele:es){
if(ele.getName()=="name"){
person.setName(ele.getText());
}else if(ele.getName()=="address"){
person.setAddress(ele.getText());
}else if(ele.getName()=="qq"){
person.setQq(Integer.parseInt(ele.getText()));
}else if(ele.getName()=="cell"){
person.setCell(Integer.parseInt(ele.getText()));
}else{
person.setSex(ele.getText());
}
}
persons.add(person);
}
return persons;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}