您的位置:首页 > 其它

SAXRead对xml文件进行读取

2015-10-26 17:05 465 查看
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.AbstractAttribute;

public class ReadXMLTest {

public static void main(String[] args){
File xmlFile = new File("D:/0_eclipse/TestDom4jFull/m.xml");  //声明在这个地方有一个文件
//没有就自动在这创建一个文件,有就不创建
try {
System.out.println(xmlFile.createNewFile());//判断是否创建了新的文件

//createNewFile()这个方法创建的文件是个空文件,只是名字叫s.xml但里面什么都没有
//创建成功时返回true
//            System.out.println(xmlFile.delete());//当文件不存在时返回false
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
//继承自InputStream的类,用于本地文件的读取,按二级制格式顺序读取,即读取到的事二级制文件流
try {
fis = new FileInputStream(xmlFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("File is not exsit!");
}

SAXReader saxReader = new SAXReader();
List rowList = null;
try {
//生成文档对应实体
Document doc = saxReader.read(fis);
//获取指定路径下的元素列表,这里指获取所有的data下的row元素
rowList = doc.selectNodes("/data/row");
} catch (DocumentException e) {
e.printStackTrace();
}

for(Iterator iter = rowList.iterator();iter.hasNext();){
//获得具体的row元素
Element element = (Element)iter.next();
//System.out.println(element.elementTextTrim("queryDTO.enterpriseId")+"test");
//获得row元素的所有属性列表
List elementList = element.attributes();
for(Iterator iter1 = elementList.iterator();iter1.hasNext();){
//将每个属性转化为一个抽象属性,然后获取其名字和值
AbstractAttribute aa = (AbstractAttribute)iter1.next();
System.out.println("Name:"+aa.getName()+";Value:"+aa.getValue());
}
//输出:
//Name:queryDTO.enterpriseId;Value:gfd
//Name:queryDTO.loginName;Value:gdfg
//Name:queryDTO.state;Value:0
System.out.println(element.getName());
//输出:
//row
// 取得row元素的queryDTO.enterpriseId属性的值
System.out.println(element.attributeValue("queryDTO.enterpriseId"));
//输出:
//gfd
//如果element下有子元素,(类似width="**"),要想获得该子元素的值,可以用如下方法
System.out.println(element.elementText("width"));//因为没有,所以输出为null。
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: