package com.netstar8.dao.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.netstar8.pojos.tree.BaseNode;
public class XmlToJavaList {
static Document doc;// 声明xml文件
static List tree = new ArrayList();
public static void main(String[] args) {
executeXml2List();
}
private static void executeXml2List() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new File("E:\\tree.xml"));
toTrans();
showNewTree();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void showNewTree() {
BaseNode node;
for(int m=0;m
node = tree.get(m);
System.out.println("id:"+node.getId()+"\n");
}
}
private static void toTrans() {
BaseNode node;
NodeList tagNodes = doc.getElementsByTagName("item");
for (int i = 0; i < tagNodes.getLength(); i++) {
NamedNodeMap atts = tagNodes.item(i).getAttributes();
node = new BaseNode();
for(int l=0;l
Node att = atts.item(l);
if(att.getNodeName().equals("id")){
node.setId(Long.parseLong(att.getNodeValue()));
}else if(att.getNodeName().equals("text")){
node.setName(att.getNodeValue());
}
System.out.println("atts"+l+":"+att.getNodeName()+"="+att.getNodeValue());
}
tree.add(node);
}
}
}
tree.xml <?xml version='1.0' encoding='iso-8859-1'?>