dom読み取りxmlと書き込みxml


今日の筆記試験のjava問題:xmlはデータを読み出して、そして読み出したデータを新しいxmlに書きます.の(書き込んだ新しいxmlファイル注意:[合格]と[非合法]の商品を2つのノードに分け、2010年7月5日以降の[合格]の商品を合算し、合否の商品の合計を算出する.2010年7月5日までの[不合格]の商品を合算する)
読み込むxmlファイル

<?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>  

書き込むxmlファイル

<?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>

具体的な実装


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;
	}
}