javaxml存儲
❶ 如何用java實現對xml文件的讀取和寫入以及保存
直接附源碼import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;import org.dom4j.*;
import org.dom4j.io.XMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSample.createDocument();
try{
dom4jSample.FileWrite(document);
Document documentStr = dom4jSample.StringToXML("<China>I Love!</China>");
dom4jSample.XMLWrite(documentStr);
Element legend = dom4jSample.FindElement(document);
System.out.println(legend.getText());
}
catch(Exception e)
{
}
}
/*
* Create a XML Document
*/
public Document createDocument()
{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age","25");
author1.addAttribute("Country","China");
author1.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age","25");
author2.addAttribute("Country","China");
author2.addText("I am great!too!");
return document;
}
/*
* Create a XML document through String
*/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelper.parseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = document.getRootElement();
Element legend = null;
for(Iterator i=root.elementIterator("legend");i.hasNext();)
{
legend = (Element)i.next();
}
return legend;
}
/*
* Write a XML file
*/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSample.xml");
document.write(out);
out.close();
}
/*
* Write a XML format file
*/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStr.xml"));
writer.write(document);
writer.close();
}
}
❷ java可以用xml存儲數據嗎
可以到是可以
但是如果存儲的是正兒八經的數據的話
建議你用ACCESS
XML用來做配置文件倒是蠻合適的
❸ 如何用java解析xml文檔,然後將數據存到資料庫里
package test11;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class XMLUtil
{
//該方法用於從XML配置文件中提取具體類類名,並返回一個實例對象
public static Object getBean()
{
try
{
//創建文檔對象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("config.xml"));
//獲取包含類名的文本節點
NodeList nl = doc.getElementsByTagName("className");
Node classNode=nl.item(0).getFirstChild();
String cName=classNode.getNodeValue();
//通過類名生成實例對象並將其返回
Class c=Class.forName(cName);
Object obj=c.newInstance();
return obj;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
<?xml version="1.0"?>
<config>
<className>test11.CatAdapter</className>
</config>
然後你吧解析處理的值放到數組或LIST或其他的你能存放的對象中。再寫SQL插入到資料庫就好了啊。主要資料庫事務處理或用批處理
❹ xml在java項目中起到的作用具體是什麼
java項目中,xml文件一般都是用來存儲一些配置信息
一般的編程, 多數用來存儲配置信息 . 拿JDBC來說,可以把資料庫連接字元串寫到xml,如果要修改數據源,只需要改xml就可以了,沒必要再去重新編譯java文件,而且,這些配置信息放在一起,別的人來讀你寫的代碼的時候,就方便了很多
框架中的xml , 除了配置信息 , 還可以寫一些對應關系,其實也是一種配置信息 .拿struts來說,xml配置的是頁面url對應後台java類(action)的關系,在配置和修改的時候,只需要改一個xml文件就可以了,沒必要一個個的查找java代碼
java項目完成之後,每個模塊應該都是獨立的,模塊之間的關系都可以使用xml來進行維護,spring就是這樣的一個框架
一個好的項目,需要有良好的可拓展性,如果把所有的邏輯關系還有配置信息都寫入代碼中,會使程序的可拓展性變差,為了解決這個問題,xml就可以對整個項目進行調度(spring)
還有使用xml作為數據儲存,不過用起來很少,多數還是用來存放配置信息
❺ java 修改了 XML 文件 如何保存文件
在修改document後,塵察亮可以使用jdk提供的Transformer講dom樹轉換成xml。
Source xmlSource = new DOMSource(document);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Result result = new StreamResult(new File("..."));
transformer.transform(xmlSource, result); // 保存dom至目的沒源文件
希望派寬能幫上你。
❻ 如何在java里長期存儲數據 不要資料庫的那種
長期存儲數據,即把數據(如內存中的)保存到可永久保存的存儲設備中(如硬碟、U盤),也就是人們常說的持久化。
常用持久化的方案有資料庫、XML文件和文件存儲。
資料庫是按照數據結構來存儲和管理數據的倉庫,後文不再做詳細介紹。
XML是可擴展標記語言,最早是為了簡化Internet的文檔數據傳輸,它提供統一的語法格式來描述數據的結構,通常XML文件用於一些少量且無特殊類型要求的文本存儲。示例代碼使用W3C標準的介面生成XML:
importjava.io.FileOutputStream;
importjava.io.PrintWriter;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.transform.OutputKeys;
importjavax.xml.transform.Transformer;
importjavax.xml.transform.TransformerFactory;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.StreamResult;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
publicclass${
publicstaticvoidmain(String[]args)throwsException{
Documentdocument=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
//創建根節點為students的XML文件
Elementstudents=document.createElement("students");
document.appendChild(students);
//在根節點下創建一個子節點學生
Elementstudent=document.createElement("student");
students.appendChild(student);
//創建節點學生姓名,值為張三
Elementname=document.createElement("name");
name.appendChild(document.createTextNode("張三"));
student.appendChild(name);
//創建節點學生年齡,值為18
Elementage=document.createElement("age");
age.appendChild(document.createTextNode("18"));
student.appendChild(age);
//創建節點學生編號,值為150101
Elementnumber=document.createElement("number");
number.appendChild(document.createTextNode("150101"));
student.appendChild(number);
//在根節點下創建第二個子節點學生
student=document.createElement("student");
students.appendChild(student);
//創建節點學生姓名,值為李四
name=document.createElement("name");
name.appendChild(document.createTextNode("李四"));
student.appendChild(name);
//創建節點學生年齡,值為20
age=document.createElement("age");
age.appendChild(document.createTextNode("20"));
student.appendChild(age);
//創建節點學生編號,值為150102
number=document.createElement("number");
number.appendChild(document.createTextNode("150102"));
student.appendChild(number);
//將XML文件保存到硬碟
Transformertransformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
PrintWriterwriter=newPrintWriter(newFileOutputStream("/home/test.xml"));
transformer.transform(newDOMSource(document),newStreamResult(writer));
}
}
無論是資料庫還是XML文件,它們都使用了能讓數據快速方便進出的標准規范。其它文件如propeties、json,都可以使用類似XML的方式來打包數據,然後通過Java豐富的io流介面保存到磁碟中。
❼ Java編寫圖書管理系統,使用XML存儲
importjava.io.File;
importjava.io.FileOutputStream;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Scanner;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
publicclassBook{
privateintno;
privateStringname;
privatedoublevalue;
publicBook(){
}
publicBook(intno,Stringname,doublevalue){
this.no=no;
this.name=name;
this.value=value;
}
publicdoublegetValue(){
returnvalue;
}
publicvoidsetValue(doublevalue){
this.value=value;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetNo(){
returnno;
}
publicvoidsetNo(intno){
this.no=no;
}
}
classBookList{
privateList<Book>bookList;
publicBookList(){
bookList=readXML();
}
publiclonggetCount(){
returnbookList.size();
}
publicList<Book>getBookList(){
returnbookList;
}
publicvoidsetBookList(List<Book>bookList){
this.bookList=bookList;
}
publicvoidadd(Bookbook){
bookList.add(book);
}
publicbooleandelete(Stringname){
Bookbook=query(name);
returnbookList.remove(book);
}
publicvoipdate(BookbookBefore,BookbookAfter){
bookList.remove(bookBefore);
add(bookAfter);
}
publicBookquery(Stringname){
Booktemp=null;
for(Bookbook:bookList){
if(book.getName().equals(name)){
temp=book;
}
}
returntemp;
}
(Bookbook){
try{
Filefile=newFile("D:\book.xml");
Documentdocument=null;
Elementroot=null;
if(!file.exists()){
//新建student.xml文件並新增內容
document=DocumentHelper.createDocument();
root=document.addElement("Books");//添加根節點
}else{
SAXReadersaxReader=newSAXReader();
document=saxReader.read(file);
root=document.getRootElement();//獲得根節點
}
ElementsecondRoot=root.addElement("Book");//二級節點
//為二級節點添加屬性,屬性值為對應屬性的值
secondRoot.addElement("no").setText(book.getNo()+"");
secondRoot.addElement("name").setText(book.getName()+"");
secondRoot.addElement("value").setText(book.getValue()+"");
OutputFormatformat=OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriterwriter=newXMLWriter(newFileOutputStream("D:\book.xml"),format);
writer.write(document);
writer.close();
document.clearContent();
}catch(Exceptione){
e.printStackTrace();
}
}
publicsynchronizedList<Book>readXML(){
List<Book>list=newArrayList<Book>();//創建list集合
Filefile=null;
try{
file=newFile("D:\book.xml");//讀取文件
if(file.exists()){
SAXReadersaxReader=newSAXReader();
Documentdocument=saxReader.read(file);
ListnodeList=document.selectNodes("Books/Book");
for(inti=0;i<nodeList.size();i++){
Elementel=(Element)nodeList.get(i);
Bookbook=newBook();
book.setNo(Integer.parseInt(el.elementText("no")));
book.setName(el.elementText("name"));
book.setValue(Double.parseDouble(el.elementText("value")));
list.add(book);
}
}
}catch(Exceptione){
e.printStackTrace();
}
returnlist;
}
}
classTest{
publicstaticvoidmain(Stringargs[]){
BookListbl=newBookList();
booleanbBreak=true;
while(bBreak){
System.out.println("請輸入操作代碼:");
System.out.println("1:添加2:刪除3:修改4:查詢5:書籍統計6:退出");
Scannersc=newScanner(System.in);
intcode=sc.nextInt();
if(code==1){
System.out.println("請輸入編號");
intno=sc.nextInt();
System.out.println("請輸入書名");
Stringname=sc.next();
System.out.println("請輸入售價");
doublevalue=sc.nextDouble();
Bookbook=newBook(no,name,value);
bl.add(book);
bl.writeXmlDocument(book);
}elseif(code==2){
System.out.println("請輸入要刪除的書籍名");
Stringname=sc.next();
if(bl.delete(name)){
System.out.println("刪除成功");
}else{
System.out.println("書籍不存在");
}
}elseif(code==3){
System.out.println("請輸入要修改的書籍名");
Stringname=sc.next();
BookbookBefore=bl.query(name);
System.out.println("請輸入新的編號");
intnewNo=sc.nextInt();
System.out.println("請輸入新的書名");
StringnewName=sc.next();
System.out.println("請輸入新的售價");
doublevalue=sc.nextDouble();
BookbookAfter=newBook(newNo,newName,value);
bl.update(bookBefore,bookAfter);
}elseif(code==4){
System.out.println("請輸入要查詢的書籍名");
Stringname=sc.next();
Bookbook=bl.query(name);
System.out.println("編號:"+book.getNo()+"書名:"+book.getName()+"售價:"+book.getValue());
}elseif(code==5){
List<Book>list=bl.getBookList();
System.out.println("總書籍數:"+bl.getCount());
for(Bookbook:list){
System.out.println("編號:"+book.getNo()+"書名:"+book.getName()+"售價:"+book.getValue());
}
}elseif(code==6){
bBreak=false;
}
}
}
}
jar 包 dom4j.jar jaxen-1.1.4.jar