package cn.com.csuinfosoft.jdom;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * title:通过JDOM操作XML
 * @author Administrator
 *
 */
public class TestJDOM {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  
  try {
   
   //1:===============================解析XML
   //解析器 SAXBuilder
   SAXBuilder builder = new SAXBuilder();
   
   //Document  加载文件生成文档树
   Document doc = builder.build( "bookinfo.xml" );
   
   //获取根节点
   Element root = doc.getRootElement();
   
   //获取第一级子节点集合  book
   List childList = root.getChildren();
   
   System.out.println( "list size:"+childList.size() );
   
   for( int i = 0; i < childList.size();i++ ){
    
    Element book = (Element)childList.get( i );
    
    System.out.println( "id:"+book.getAttributeValue( "id" ) );
    
    //bookname  getChild:获取子节点   getChildText:获取子节点的内容
    Element bookname = book.getChild( "bookname" );
    System.out.println( "bookname:"+bookname.getText() );
    
    System.out.println( "author:"+book.getChildText( "author" ) );   
    System.out.println( "price:"+book.getChildText( "price" ) ); 
    System.out.println( "age:"+book.getChildText( "age" ) );
    System.out.println( "type:"+book.getChildText( "type" ) );
  
    System.out.println( "+++++++++++++++++++++++++++++++++++++++++++" );
 
   }
   
   
   //2输出xml================================================
   Document document = new Document();
   
   //根节点
   Element bookRoot = new Element( "bookinfo" );
   
   //book
   Element book = new Element( "book" );
   
   //设置属性
   book.setAttribute( "id","101" );
   //Attribute:属性对像
   Attribute attr = new Attribute( "title","计算机" );
   
   book.setAttribute( attr );
   
   //bookname
   Element bookname = new Element( "bookname" );
   
   //添加内容
   bookname.setText( "servlet,jsp" );
   
   //add
   book.addContent( bookname );
   bookRoot.addContent( book );
   document.addContent( bookRoot );
   
   //输出 XMLOutputter
   XMLOutputter out = new XMLOutputter();
   
   //把指定的XML文档输出到指定的文件中
   out.output( document, new FileOutputStream( "booklist.xml" ));
 
  } catch (JDOMException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}