package csm.doxml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import java.util.ArrayList;
/*读取xml文件并返回根结点,第一个子结点名字,第一个子结点的属性列*
*
**/
public class ReadXmlF{
public Element root=null;/*根结点*/
public String type=null;/*第一个结点类型名字*/
public ArrayList subNodeList=new ArrayList();/*子结点类型名字*/
String filename="product.xml";
ArrayList LevelOne=new ArrayList();
public ReadXmlF(){}
public ReadXmlF(String filenames){
filename=filenames;
}
protected int readXML()throws Exception{
/*创建文档实例*/
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
NodeList children=null;/*子结点的子结点*/
try{
db=dbf.newDocumentBuilder();
}catch(ParserConfigurationException e1){
printf(":"+e1.getMessage());
return -1;
}
Document doc=null;
try{
doc=db.parse(filename);
}
catch(DOMException e2){
printf(":"+e2.getMessage());
return -2;
}
catch(Exception e3){
printf(e3.getMessage());
return -3;
}
/*开始取根*/
root=doc.getDocumentElement();
/*取第一个子结点类型*/
if(root!=null)
{
children=root.getChildNodes();
int len=children.getLength();
printf("root.length=:"+String.valueOf(len));
if(children.getLength()>0)//nodelist下标从1开始
for(int k=0;(2*k+1){
type=String.valueOf(children.item(2*k+1).getNodeName());
LevelOne.add(type);
}
}
/*再取第二层结点的子结点*/
Node peak = children.item(1);
for (int j=1; j {
String typename=String.valueOf(peak.getChildNodes().item(j++).getNodeName());
subNodeList.add(typename);
/**/printf("ch3:"+typename);
}
return 1;
}
/*返回第一层子结点名字*/
public ArrayList getFirstType(){
if(LevelOne.size()>0) return LevelOne;
else return null;
}
/*返回第一层个子结点名字*/
protected ArrayList getSubNode(){
if(subNodeList.size()>0)return subNodeList;
return null;
}
/*返回根结点*/
protected Element getRoot(){
if(root!=null)return root;
return null;
}
private void printf(String content){
System.out.println(content);
}
public static void main(String[] args){
ReadXmlF rf=new ReadXmlF("test2.xml");
Element ro=null;
try{int flags=rf.readXML();
ArrayList a=rf.getFirstType();
System.out.println("s1="+a.size());
//for(int i=0;i// System.out.println("s1="+String.valueOf(a.get(i)));
//ro=rf.getRoot();
}catch(Exception e){}
if(ro==null)
System.out.println("ro is null");
else
System.out.println("ro is not null");
}
}
101
Kiran
Pai
22
12300
102
Bill
Gates
22
12300
103
Steve
Jobs
22
12300
104
joe
singh
25
6300