dom读取xml与写入xml

[b]今天笔试的java题:xml读出数据,并把读出来的数据写入一个新的xml中。。。(写入的新xml文件注意:[合格]与[不合法]的商品分为两个分节点,把在2010年7月5号之后的为[合格]的商品,并计算合格商品的总和。把在2010年7月5号之前的为[不合格]的商品,并计算合格商品的总和)[/b]

[color=red]要读取的xml文件[/color]

<?xml version="1.0" encoding="utf-8"?>

<main>
<user>admin</user>
<vailddate>2010-7-11</vailddate>

<item>
<nameNo>no1</nameNo>
<product>黄果</product>
<price>120</price>
<date>2010-7-5</date>
</item>

<item>
<nameNo>no2</nameNo>
<product>苹果</product>

<price>67</price>
<date>2010-6-21</date>
</item>

<item>
<nameNo>no3</nameNo>
<product>香蕉</product>
<price>99</price>
<date>2010-7-8</date>
</item>

<item>
<nameNo>no4</nameNo>
<product>梨子</product>
<price>188</price>
<date>2010-6-11</date>
</item>

<item>
<nameNo>no5</nameNo>
<product>桃子</product>
<price>55</price>
<date>2010-9-18</date>
</item>

<item>
<nameNo>no6</nameNo>
<product>西瓜</product>
<price>36</price>
<date>2010-10-8</date>
</item>

<item>
<nameNo>no7</nameNo>
<product>草莓</product>
<price>88</price>
<date>2010-8-28</date>
</item>

<item>
<nameNo>no8</nameNo>
<product>西红柿</product>
<price>12</price>
<date>2010-7-12</date>
</item>

</main>


[color=red]要写入的xml文件[/color]

<?xml version="1.0" encoding="GBK"?>

<products>

<user></user>
<vaiDate></vaiDate>

<passProduct>
<PassNo></PassNo>
<PassName></PassName>
<PassSumPrice></PassSumPrice>
<PassDate></PassDate>
</passProduct>

<noPassProduct>
<noPassNo></noPassNo>
<noPassName></noPassName>
<noPassSumPrice></noPassSumPrice>
<noPassDate></noPassDate>
</noPassProduct>

</products>


[color=red]具体实现[/color]



import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.xerces.parsers.DOMParser;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;



public class DOMRederAndWrite
{
public static void main( String[] args )
{
DOMRederAndWrite dom=new DOMRederAndWrite();
//读xml
Products pros=dom.getReaderXml("E://x.xml");
//写xml
dom.writeXml(pros, "E://new.xml");
}

//xml文件的读取
public Products getReaderXml(String fileName){
//用来在存放xml数据
Products pros=new Products();
try{

//获得dom解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//构造DOM解析器的实例
DocumentBuilder db = dbf.newDocumentBuilder();
//开始解析文档,将XML文档转换成DOM树存入内存;
Document doc=db.parse(fileName);
//获取root节点;
Element els=doc.getDocumentElement();

//DOMParser类封装了dom解析器工厂只能读
/* DOMParser parser=new DOMParser();
parser.parse(fileName);
Document d=parser.getDocument();
Element el=d.getDocumentElement();
*/
// System.out.println(els+"-"+el);

NodeList user=els.getElementsByTagName("user");
Element us=(Element)user.item(0);
String u=us.getFirstChild().getNodeValue();
pros.setMainUser(u);

NodeList vail=els.getElementsByTagName("vailddate");
Element va=(Element)vail.item(0);
String v=va.getFirstChild().getNodeValue();
pros.setVaildDate(v);

// System.out.println(u+" "+v);

NodeList list=els.getElementsByTagName("item");
for(int i=0;i<list.getLength();i++){
Element e=(Element)list.item(i);
List<String> lists=new ArrayList<String>();

NodeList name=e.getElementsByTagName("nameNo");
String n=name.item(0).getFirstChild().getNodeValue();
lists.add(n);

NodeList product=e.getElementsByTagName("product");
String p=product.item(0).getFirstChild().getNodeValue();
lists.add(p);

NodeList price=e.getElementsByTagName("price");
String pri=price.item(0).getFirstChild().getNodeValue();
lists.add(pri);

NodeList date=e.getElementsByTagName("date");
String ds=date.item(0).getFirstChild().getNodeValue();
lists.add(ds);

pros.getLists().add(lists);
// System.out.println(n+" "+p+" "+pri+" "+ds);
}
}catch(Exception e){
e.printStackTrace();
}
return pros;
}

//xml文件的写入
public void writeXml(Products pro,String fileName){

try{
//要筛选的时间
SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
Date newDate=sim.parse("2010-7-5");

//叠加合格与不合格商品合集
String no="";
String name="";
float price=0;
String date="";

String failno="";
String failname="";
float failprice=0;
String faildate="";
//筛选2010-7-5之后的日期
for(int j=0;j<pro.getLists().size();j++){
List ls=(ArrayList)pro.getLists().get(j);
Date oldDate=sim.parse(ls.get(3).toString());
//合格与不合格的商品
if(newDate.getTime()<oldDate.getTime()){
no=no+ls.get(0)+" ";
name=name+ls.get(1)+" ";
price=price+Float.parseFloat(ls.get(2).toString());
date=date+ls.get(3)+" ";

}else{
failno=failno+ls.get(0)+" ";
failname=failname+ls.get(1)+" ";
failprice=failprice+Float.parseFloat(ls.get(2).toString());
faildate=faildate+ls.get(3)+" ";
}
}

System.out.println("[合格]的商品:"+no+"-"+name+"-"+price+"-"+date);
System.out.println("[不合格]的商品:"+failno+"-"+failname+"-"+failprice+"-"+faildate);
//获得dom解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//构造DOM解析器的实例
DocumentBuilder db = dbf.newDocumentBuilder();
//创建一个新的xml文档
Document newDoc=db.newDocument();
//创建根结点
Element root=newDoc.createElement("products");
//创建子结点
Element child=newDoc.createElement("passProduct");
//创建子结点
Element noPassChild=newDoc.createElement("noPassProduct");
//创建子结点
Element users=newDoc.createElement("user");
//user添加文本结点
users.appendChild(newDoc.createTextNode(pro.getMainUser()));
//创建子结点
Element vaildates=newDoc.createElement("vaiDate");
//vaildates添加文本结点
vaildates.appendChild(newDoc.createTextNode(pro.getVaildDate()));

//根结点下添加子结点
root.appendChild(users);
root.appendChild(vaildates);
root.appendChild(child);
root.appendChild(noPassChild);

//设置子结点上的属性
// child.setAttribute("name","xiaoming");

Element names=newDoc.createElement("PassName");
names.appendChild(newDoc.createTextNode(name));

Element nos=newDoc.createElement("PassNo");
nos.appendChild(newDoc.createTextNode(no));

Element prices=newDoc.createElement("PassSumPrice");
prices.appendChild(newDoc.createTextNode(price+""));

Element dates=newDoc.createElement("PassDate");
dates.appendChild(newDoc.createTextNode(date));

//【合格】子结点下添加子结点
child.appendChild(nos);
child.appendChild(names);
child.appendChild(prices);
child.appendChild(dates);

Element failNames=newDoc.createElement("noPassName");
failNames.appendChild(newDoc.createTextNode(failname));

Element failNos=newDoc.createElement("noPassNo");
failNos.appendChild(newDoc.createTextNode(failno));

Element failPrices=newDoc.createElement("noPassSumPrice");
failPrices.appendChild(newDoc.createTextNode(failprice+""));

Element failDates=newDoc.createElement("noPassDate");
failDates.appendChild(newDoc.createTextNode(faildate));

//【不合格】子结点下添加子结点
noPassChild.appendChild(failNos);
noPassChild.appendChild(failNames);
noPassChild.appendChild(failPrices);
noPassChild.appendChild(failDates);

//在dom下添加根节点
newDoc.appendChild(root);
//创建一个xml字节输入流设置字符编号集
OutputFormat format = new OutputFormat( newDoc , "GBK" , true );
//创建一个字符输入流
StringWriter stringOut = new StringWriter();
//创建xml连续
XMLSerializer serial = new XMLSerializer( stringOut, format );
serial.asDOMSerializer();
serial.serialize( newDoc.getDocumentElement() );
//创建dom写入流
PrintStream ps = new PrintStream(new FileOutputStream(fileName));
ps.println(stringOut.toString());

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

}


//存放读取xml文件中的数据
class Products{

private String mainUser;
private String vaildDate;
private List<Object> lists=new ArrayList<Object>();

public String getMainUser() {
return mainUser;
}
public void setMainUser(String mainUser) {
this.mainUser = mainUser;
}
public String getVaildDate() {
return vaildDate;
}
public void setVaildDate(String vaildDate) {
this.vaildDate = vaildDate;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值