xml 简单例子

package test;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class TestSax {
 public static void main(String args[]) {
     File documentFile = new File("BookName.xml");

     Document doc = null;
     try {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//是实例化一个DocumentBuilderFactory对象
       DocumentBuilder dbObj = dbf.newDocumentBuilder();//创建工厂实例
       doc = dbObj.parse(documentFile);
     }
     catch (java.io.IOException e) {
       e.printStackTrace();
     }
     catch (Exception e) {
       e.printStackTrace();
     }
    
     //
     Element root = doc.getDocumentElement();
     System.out.println("根节点为"+ root.getNodeName() + "./n");
    
     NodeList childrenList = root.getChildNodes();// 得到根元素所有子节点的集合 (list)
     System.out.print("长度"+ childrenList.getLength() +"./n");//子节点的长度
     System.out.print("------------- /n");
    
    
     /*
      * 将xml换行解析为
      * <?xml version="1.0"?>
   * <books><title>谁动了我的奶酪</title> 
   * <booktitle>罗密欧与茱莉叶</booktitle>  ----->每行加入的回车,换行,空格,都会变成 childNode.TEXT_NODE类型解析,想解析准确必须全部都去掉,拍成一行
   * <title>白雪公主</title>
   * <title>风水</title>
   * </books>
      * */
     for (Node childNode = root.getFirstChild(); childNode != null;childNode = childNode.getNextSibling()) {
       if (childNode.getNodeType() == childNode.TEXT_NODE) {
         System.out.println( childNode.getNodeName() + "===xxx1===" +childNode.getNodeValue());
       }
       else if (childNode.getNodeType() == childNode.ELEMENT_NODE) {
         System.out.println(childNode.getNodeName() + "===xxx2===" +childNode.getFirstChild().getNodeValue());
       }
     }
    
    
     NodeList bookList = root.getElementsByTagName("title");//获得节点
    
     Element bookElement;
     for (int bookNum = 0; bookNum < bookList.getLength(); bookNum++) {
       bookElement = (Element) bookList.item(bookNum);

       bookElement.setAttributeNode(doc.createAttribute("bookNumber"));//建立属性bookNumber节点
       bookElement.setAttribute("bookNumber", ("Book : " + (bookNum + 1)));//设置属性节点值("节点名","值")
       String bookName = bookElement.getFirstChild().getNodeValue();//本子节点的第一个节点的值
       System.out.println("bookName"+bookName);
       bookElement.getFirstChild().setNodeValue(bookName.toUpperCase());//转换大写

       Element updateElement = doc.createElement("published");//建立一个新的节点
       java.util.Date rightNow = new java.util.Date();//获得时间
       Node updateText = doc.createTextNode(rightNow.toString());//设置新的节点的值

       updateElement.appendChild(updateText);//新建节点加入文字节点值
       bookElement.appendChild(updateElement);//每个子节点加入新建的节点
     }
    
     try {
       String outputFile = "NewBookName.xml";

       DOMSource source = new DOMSource(doc);//创建带有 DOM 节点的新输入源
       StreamResult result = new StreamResult(new FileOutputStream(outputFile));//充当转换结果的持有者,可以为 XML、纯文本、HTML 或某些其他格式的标记

       TransformerFactory transFactory = TransformerFactory.newInstance();//实例化一个写入
       Transformer transformer = transFactory.newTransformer();
      
       /*
        * source - 要转换的 XML 输入。
     * result - 转换 xmlSource 的 Result。
        * */
       //将 XML Source 转换为 Result。当实例化 Transformer 和对 Transformer 实例进行任何修改时,指定的转换行为由 TransformerFactory 的实际设置决定。
       transformer.transform(source, result);

     }
     catch (Exception e) {
       e.printStackTrace();
     }
   }
}
 

 

 

================================JDOM===============================================

package com.ajaxlab.ajax;

import org.jdom.*;
import org.jdom.input.*;
import java.util.*;

public class ClassService {
 private Document dom;
 /**
  * 构造函数,初始化XML文档根结点
  *
  */
 public ClassService() {
  try {
   
   //this.dom = builder.build(new File("/ajaxlab/src/com/ajaxlab/ajax/products.xml"));
   //this.dom = builder.build(ClassService.class.getClassLoader().getResourceAsStream("products.xml"));
   SAXBuilder builder = new SAXBuilder();
   this.dom = builder.build(ClassService.class.getResource("products.xml"));
  }catch(Exception ex) {
   System.out.println(ex.toString());
  }
 }
 /**
  * 取得XML文档第一级结点
  * @return
  */
 public ProductClass[] getAllClass1() {
  Collection products = new ArrayList();//放产品的ArrayList
  Iterator iterator = this.dom.getRootElement().getChildren().iterator();//得到根元素,得到根元素所有子元素的集合,得到迭代器(得到第一层根)
  do {
   Element element = (Element)iterator.next();//得到第一个元素
   ProductClass product = new ProductClass(element.getAttributeValue("id"),element.getAttributeValue("className"));//将id值,className值放入每个产品类中
   products.add(product);//放入ArrayList 里
  }while(iterator.hasNext());
  return (ProductClass[])products.toArray(new ProductClass[0]);//强转返回ProductClass []数组
 }
 /**
  * 取得XML文档指定的第二级结点
  * @param class1Id
  * @return
  */
 public ProductClass[] getClass2ById(String class1Id) {
  Collection products = new ArrayList();
  Element class1Element = null;
  Iterator iterator = this.dom.getRootElement().getChildren().iterator();//得到根元素,得到根元素所有子元素的集合,得到迭代器(得到第一层根)
  do {
   Element element = (Element)iterator.next();//得到第一个元素
   
   if(class1Id.equalsIgnoreCase(element.getAttributeValue("id"))) {//循环每个元素的id,根据传入id获得元素
    class1Element = element;
    break;
   }
  }while(iterator.hasNext());
  
  if(class1Element!=null) {//当获得元素不为空
   Iterator iter = class1Element.getChildren().iterator();//得到根元素所有子元素的集合,得到迭代器(得到第二层根)
   do {
    Element element = (Element)iter.next();
    ProductClass product = new ProductClass(element.getAttributeValue("id"),element.getAttributeValue("className"));//将id值,className值放入每个产品类中
    products.add(product);//放入ArrayList 里
   }while(iter.hasNext());
   return (ProductClass[])products.toArray(new ProductClass[0]);
  }
  else return null;
 }
 /**
  * 取得XML文档指定的第三级结点
  * @param class1Id
  * @param class2Id
  * @return
  */
 public ProductClass[] getClass3ById(String class1Id,String class2Id) {
  Collection products = new ArrayList();
  Element class1Element = null;
  Element class2Element = null;
  
  Iterator iterator = this.dom.getRootElement().getChildren().iterator();//得到根元素,得到根元素所有子元素的集合,得到迭代器(得到第一层根)
  do {
   Element element = (Element)iterator.next();
   if(class1Id.equalsIgnoreCase(element.getAttributeValue("id"))) {
    class1Element = element;
    break;
   }
  }while(iterator.hasNext());
  
  if(class1Element!=null) {
   Iterator iter = class1Element.getChildren().iterator();//得到根元素所有子元素的集合,得到迭代器(得到第二层根)
   do {
    Element element = (Element)iter.next();
    if(class2Id.equalsIgnoreCase(element.getAttributeValue("id"))) {
     class2Element = element;
     break;
    }
   }while(iter.hasNext());
   
   if(class2Element!=null) {
    Iterator iter2 = class2Element.getChildren().iterator();//得到根元素所有子元素的集合,得到迭代器(得到第三层根)
    do {
     Element element = (Element)iter2.next();
     ProductClass product = new ProductClass(element.getAttributeValue("id"),element.getAttributeValue("className"));
     products.add(product);
    }while(iter2.hasNext());
   }
   return (ProductClass[])products.toArray(new ProductClass[0]);
  }
  else return null;
 }
 
 public static void main(String[] args) {
  try {
   ClassService service = new ClassService();
   System.out.println(service.getAllClass1().length);
   System.out.println(service.getClass2ById("2").length);
   System.out.println(service.getClass3ById("1","1").length);
  }catch(Exception ex) {
   ex.printStackTrace();
  }
 }
}
-----------------------------------------------------------------------------------------------------------------------------------------------

面是实例用的XML文件:

<?xml version="1.0" encoding="GBK"?>
<书库>
<书>
<书名>Java编程入门</书名>
<作者>张三</作者>
<出版社>电子出版社</出版社>
<价格>35.0</价格>
<出版日期>2002-10-07</出版日期>
</书>
<书>
<书名>XML在Java中的应用</书名>
<作者>李四</作者>
<出版社>希望出版社</出版社>
<价格>92.0</价格>
<出版日期>2002-10-07</出版日期>
</书>
</书库>

下面是操作XML文件的Bean:
package xml;
/**
* XML的读写操作Bean
*/
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class XmlBean{
private String bookname,author,pub,price,pubdate;
public String getbookname() { return bookname;}
public String getauthor() { return author;}
public String getpub() { return pub;}
public String getprice() { return price;}
public String getpubdate() { return pubdate;}
public void setbookname(String bookname) { this.bookname =bookname ; }
public void setauthor(String author) { this.author =author; }
public void setpub(String pub) { this.pub =pub ; }
public void setprice(String price) { this.price =price ; }
public void setpubdate(String pubdate) { this.pubdate =pubdate ; }
public XmlBean(){}
/**
* 读取XML文件所有信息
*/
public Vector LoadXML(String path)throws Exception{
Vector xmlVector = null;
FileInputStream fi = null;
try{
fi = new FileInputStream(path);
xmlVector = new Vector();
SAXBuilder sb = new SAXBuilder();//构造方法
Document doc = sb.build(fi);    //放入文件路径
Element root = doc.getRootElement(); //得到根元素
List books = root.getChildren(); //得到根元素所有子元素的集合(list)

Element book =null;
XmlBean xml =null;// 存放容器
for(int i=0;i<books.size();i++){
xml = new XmlBean();
book = (Element)books.get(i ); //得到第一本书元素
xml.setbookname(book.getChild("书名").getText());
xml.setauthor(book.getChild("作者").getText());
xml.setpub(book.getChild("出版社").getText());
xml.setprice(book.getChild("价格").getText());
xml.setpubdate(book.getChild("出版日期").getText());
xmlVector.add(xml);
}
}
catch(Exception e){
System.err.println(e+"error");
}
finally{
try{
fi.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return xmlVector;
}
/**
* 删除XML文件指定信息
*/
public static void DelXML(HttpServletRequest request)throws Exception{
FileInputStream fi = null;
FileOutputStream fo = null;
try{
String path=request.getParameter("path");                        //传入文件路径
int xmlid=Integer.parseInt(request.getParameter("id"));  //(传入id)
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();  //构造方法
Document doc = sb.build(fi);     //放入文件
Element root = doc.getRootElement(); //得到根元素
List books = root.getChildren(); //得到根元素所有子元素的集合
books.remove(xmlid);//删除指定位置的子元素(传入id)

String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK"); //重新写入XMl("",true,"GBK")
fo=new FileOutputStream(path); //写入路径
outp.output(doc,fo);    //(Document ,FileOutputStream )
}
catch(Exception e){
System.err.println(e+"error");
}
finally{
try{
fi.close();
fo.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 添加XML文件指定信息
*/
public static void AddXML(HttpServletRequest request)throws Exception{
FileInputStream fi = null;
FileOutputStream fo = null;
try{
String path=request.getParameter("path");
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); //得到根元素
List books = root.getChildren(); //得到根元素所有子元素的集合

String bookname=request.getParameter("bookname");
String author=request.getParameter("author");
String price=request.getParameter("price");
String pub=request.getParameter("pub");
String pubdate=request.getParameter("pubdate");
Text newtext;
Element newbook= new Element("书");
Element newname= new Element("书名");
newname.setText(bookname);  //设置文本

newbook.addContent(newname);   //增加内容
Element newauthor= new Element("作者");
newauthor.setText(author);
newbook.addContent(newauthor);
Element newpub= new Element("出版社");
newpub.setText(pub);
newbook.addContent(newpub);
Element newprice= new Element("价格");
newprice.setText(price);
newbook.addContent(newprice);
Element newdate= new Element("出版日期");
newdate.setText(pubdate);
newbook.addContent(newdate);
books.add(newbook);//增加子元素  ,list.add增加内容
String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");
fo=new FileOutputStream(path);
outp.output(doc,fo);  /写入

}
catch(Exception e){
System.err.println(e+"error");
}
finally{
try{
fi.close();
fo.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 修改XML文件指定信息
*/
public static void EditXML(HttpServletRequest request)throws Exception{
FileInputStream fi = null;
FileOutputStream fo = null;
try{
String path=request.getParameter("path");
int xmlid=Integer.parseInt(request.getParameter("id"));
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); //得到根元素
List books = root.getChildren(); //得到根元素所有子元素的集合
Element book=(Element)books.get(xmlid);   //获得传入要修改的第几个id

String bookname=request.getParameter("bookname");
String author=request.getParameter("author");
String price=request.getParameter("price");
String pub=request.getParameter("pub");
String pubdate=request.getParameter("pubdate");
Text newtext;
Element newname= book.getChild("书名");   //获得以书名为"节点"的元素
newname.setText(bookname);//修改书名为新的书名

Element newauthor= book.getChild("作者");
newauthor.setText(author);
Element newpub= book.getChild("出版社");
newpub.setText(pub);
Element newprice= book.getChild("价格");
newprice.setText(price);
Element newdate= book.getChild("出版日期");
newdate.setText(pubdate);
//books.set(xmlid,book);//修改子元素
String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");
fo=new FileOutputStream(path);
outp.output(doc,fo);//写入

}
catch(Exception e){
System.err.println(e+"error");
}
finally{
try{
fi.close();
fo.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值