本文目录一览:
- 1、在java在如何解析XML文件
- 2、java解析json格式文件,再保存在数据库怎么做?
- 3、如何用java解析CSV文件
- 4、java 怎样解析 excel生成的xml文件
- 5、Java里面怎么解析xml文件的内容
在java在如何解析XML文件
在java环境下读取xml文件的方法主要有4种:DOM、SAX、JDOM、JAXB
1. DOM(Document Object Model)
此方法主要由W3C提供,它将xml文件全部读入内存中,然后将各个元素组成一棵数据树,以便快速的访问各个节点 。 因此非常消耗系统性能 ,对比较大的文档不适宜采用DOM方法来解析。 DOM API 直接沿袭了 XML 规范。每个结点都可以扩展的基于 Node 的接口,就多态性的观点来讲,它是优秀的,但是在 Java 语言中的应用不方便,并且可读性不强。
实例:
import javax.xml.parsers.*;
//XML解析器接口
import org.w3c.dom.*;
//XML的DOM实现
import org.apache.crimson.tree.XmlDocument;
//写XML文件要用到
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//允许名字空间
factory.setNamespaceAware(true);
//允许验证
factory.setValidating(true);
//获得DocumentBuilder的一个实例
try {
DocumentBuilder builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
// 出异常时输出异常信息,然后退出,下同
System.exit(1);
}
//解析文档,并获得一个Document实例。
try {
Document doc = builder.parse(fileURI);
} catch (DOMException dom) {
System.err.println(dom.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
//获得根节点StuInfo
Element elmtStuInfo = doc.getDocumentElement();
//得到所有student节点
NodeList nlStudent = elmtStuInfo.getElementsByTagNameNS(
strNamespace, "student");
for (……){
//当前student节点元素
Element elmtStudent = (Element)nlStudent.item(i);
NodeList nlCurrent = elmtStudent.getElementsByTagNameNS(
strNamespace, "name");
}
java解析json格式文件,再保存在数据库怎么做?
java解析json格式文件,再保存在数据库的方法:
1:定义一个实体类
2:用json lib将json字符串转为Java对象
3:用jdbc或hibernate将java对象存入数据库
直接读写文件,再把读出来的文件内容格式化成json,再用JDBC、Mybatis或者其他框架将json数据存入数据库。
假设实体类是这样的:
public class ElectSet {
public String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
public String getXueqi() {
return xueqi;
}
public void setXueqi(String xueqi) {
this.xueqi = xueqi;
}
public String getXuenian() {
return xuenian;
}
public void setXuenian(String xuenian) {
this.xuenian = xuenian;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getMenshu() {
return menshu;
}
public void setMenshu(int menshu) {
this.menshu = menshu;
}
public String getIsReadDB() {
return isReadDB;
}
public void setIsReadDB(String isReadDB) {
this.isReadDB = isReadDB;
}
}
有一个json格式的文件,存的信息如下:
Sets.json:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}
具体操作:
/*
* 取出文件内容,填充对象
*/
public ElectSet findElectSet(String path){
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//获得json文件的内容
JSONObject jo=JSONObject.fromObject(sets);//格式化成json对象
//System.out.println("------------" jo);
//String name = jo.getString("xuenian");
//System.out.println(name);
electset.setXueqi(jo.getString("xueqi"));
electset.setXuenian(jo.getString("xuenian"));
electset.setStartTime(jo.getString("startTime"));
electset.setEndTime(jo.getString("endTime"));
electset.setMenshu(jo.getInt("menshu"));
electset.setIsReadDB(jo.getString("isReadDB"));
return electset;
}
//设置属性,并保存
public boolean setElect(String path,String sets){
try {
writeFile(path,sets);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//读文件,返回字符串
public String ReadFile(String path){
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try {
//System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " line ": " tempString);
laststr = laststr tempString;
line ;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
将获取到的字符串,入库即可。
如何用java解析CSV文件
思想:先获取csv文件的路径,通过BufferedReader类去读该路径中的文件,使用readLine方法进行逐行读取。
注意:使用readLine方法后会自动转到下一行。因此在判断是否为空后得先将读取到的内容赋值给一变量,在循环中使用该变量即可。
public static void main(String[] args)
{
File csv = new File("C:\\Users\\chenxumin\\Desktop\\Result.csv"); // CSV文件路径
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(csv));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
String line = "";
String everyLine = "";
try {
ListString allString = new ArrayList();
while ((line = br.readLine()) != null) //读取到的内容给line变量
{
everyLine = line;
System.out.println(everyLine);
allString.add(everyLine);
}
System.out.println("csv表格中所有行数:"+allString.size());
} catch (IOException e)
{
e.printStackTrace();
}
}
java 怎样解析 excel生成的xml文件
java解析excel生成的xml文件的方法是使用dom4j实现的。
dom4j是一个简单的开源库,用于处理XML、 XPath和XSLT,它基于Java平台,使用Java的集合框架,全面集成了DOM,SAX和JAXP。
1、excel生成的xml样例文件:
?xml version="1.0"?
?mso-application progid="Excel.Sheet"?
Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html=""
DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"
Created2006-09-16T00:00:00Z/Created
LastSaved2016-07-25T03:26:50Z/LastSaved
Version14.00/Version
/DocumentProperties
OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"
AllowPNG/
RemovePersonalInformation/
/OfficeDocumentSettings
ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"
WindowHeight7956/WindowHeight
WindowWidth14808/WindowWidth
WindowTopX240/WindowTopX
WindowTopY168/WindowTopY
ActiveSheet2/ActiveSheet
ProtectStructureFalse/ProtectStructure
ProtectWindowsFalse/ProtectWindows
/ExcelWorkbook
Styles
Style ss:ID="Default" ss:Name="Normal"
Alignment ss:Vertical="Bottom"/
Borders/
Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/
Interior/
NumberFormat/
Protection/
/Style
Style ss:ID="s16" ss:Name="好"
Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#006100"/
Interior ss:Color="#C6EFCE" ss:Pattern="Solid"/
/Style
Style ss:ID="s17"
Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:Indent="1"
ss:WrapText="1"/
Font ss:FontName="宋体" x:CharSet="134" ss:Size="8" ss:Color="#686868"/
NumberFormat ss:Format="@"/
/Style
Style ss:ID="s18" ss:Parent="s16"
Alignment ss:Vertical="Bottom"/
/Style
Style ss:ID="s19"
NumberFormat ss:Format="yyyy/m/d\ h:mm:ss"/
/Style
/Styles
Worksheet ss:Name="Sheet1"
Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="3" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="14.4"
Row
CellData ss:Type="String"工号/Data/Cell
CellData ss:Type="String"姓名 /Data/Cell
Cell ss:Index="5"Data ss:Type="String"工号/Data/Cell
CellData ss:Type="String"姓名/Data/Cell
/Row
Row
CellData ss:Type="Number"111/Data/Cell
CellData ss:Type="String"张三/Data/Cell
Cell ss:Index="5"Data ss:Type="Number"111/Data/Cell
Cell ss:Formula="=VLOOKUP(R2C5:R3C5,RC[-5]:R[1]C[-4],2)"Data
ss:Type="String"张三/Data/Cell
/Row
Row
CellData ss:Type="Number"112/Data/Cell
CellData ss:Type="String"李四/Data/Cell
Cell ss:Index="5"Data ss:Type="Number"112/Data/Cell
Cell ss:Formula="=VLOOKUP(R2C5:R3C5,RC[-5]:R[1]C[-4],2)"Data
ss:Type="String"李四/Data/Cell
/Row
/Table
WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"
PageSetup
Header x:Margin="0.3"/
Footer x:Margin="0.3"/
PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/
/PageSetup
Panes
Pane
Number3/Number
ActiveRow7/ActiveRow
ActiveCol5/ActiveCol
/Pane
/Panes
ProtectObjectsFalse/ProtectObjects
ProtectScenariosFalse/ProtectScenarios
/WorksheetOptions
/Worksheet
/Workbook
2、java解析代码:
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("person.xml"));
Element root = document.getRootElement();
Iterator it = root.elementIterator();
while (it.hasNext()) {
Element element = (Element) it.next();
//未知属性名称情况下
/*Iterator attrIt = element.attributeIterator();
while (attrIt.hasNext()) {
Attribute a = (Attribute) attrIt.next();
System.out.println(a.getValue());
}*/
//已知属性名称情况下
System.out.println("id: " + element.attributeValue("id"));
//未知元素名情况下
/*Iterator eleIt = element.elementIterator();
while (eleIt.hasNext()) {
Element e = (Element) eleIt.next();
System.out.println(e.getName() + ": " + e.getText());
}
System.out.println();*/
//已知元素名情况下
System.out.println("title: " + element.elementText("title"));
System.out.println("author: " + element.elementText("author"));
System.out.println();
}
}
}
Java里面怎么解析xml文件的内容
Java解析xml代码,我是用dom4j读取的,
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4JReader {
public Dom4JReader() {
}
/**
*
* @Function 获取xml文件里符合要求的数据
*/
public void getDom() {
SAXReader sr = new SAXReader();
try {
//获取applicationContext.xml文件的对象
Document doc = sr.read(new File("applicationContext.xml"));
//获得跟节点
Element root = doc.getRootElement();
//// 枚举所有子节点
for (Iterator i = root.elementIterator("bean"); i.hasNext();) {
//获取bean节点
Element bean = (Element) i.next();
// 枚举名称为bean的节点
for (Iterator j = bean.attributeIterator(); j.hasNext();) {
//获取bean节点的所有属性
Attribute attr = (Attribute) j.next();
//判断属性的值如果为fileUploadBo
if (attr.getText().equals("fileUploadBo")) {
//打印出这个bean节点的所有信息
System.out.println(bean.asXML());
}
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
这段代码要执行的话,要导入dom4j的包,还有
//获取applicationContext.xml文件的对象
Document doc = sr.read(new File("applicationContext.xml"));
在src下有这个xml文件。