Monday, 1 August 2011

Use JDOM to build a document

  
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.util.*;
import java.io.*;

public class JDOMTest {

  public static void showBooksElement root ) {
       List books = root.getChildren"book" );
       forIterator i=books.iterator(); i.hasNext()) {
         Element book = Element )i.next();
         System.out.println"Book: " + book.getAttributeValue"category" ", " +
                             book.getChildTextTrim"title" ", " +
                             book.getChildTextTrim"author" ", " 
                             book.getChildTextTrim"price" ) );
       }
  }


  public static void mainString[] args throws Exception
       SAXBuilder builder = new SAXBuilder();
       Document doc = builder.build"book.xml" );
       Element root = doc.getRootElement();
       System.out.println"Book List Before: " );
       showBooksroot );

       // Add a new book
       Element newBook = new Element"book" );
       newBook.setAttribute"category""fiction" );
       Element newTitle = new Element"title" );
       newTitle.addContent"Desecration" );
       Element newAuthor = new Element"author" );
       newAuthor.addContent"Tim LaHaye" );
       Element newPrice = new Element"price" );
       newPrice.addContent"19.95" );
       newBook.addContentnewTitle );
       newBook.addContentnewAuthor );
       newBook.addContentnewPrice );
       root.addContentnewBook );

       System.out.println"Book List After: " );
       showBooksroot );

       XMLOutputter out = new XMLOutputter"  "true );
       out.outputroot, System.out );
  }
}

<books> 
  <book category="fiction"
    <title>title 1</title> 
    <author>Tim Lahaye</author> 
    <price>14.95</price> 
  </book> 
  <book category="science fiction"
    <title>title 2</title> 
    <author>Tim Lahaye</author> 
    <price>14.95</price> 
  </book> 

</books> 

   
    
  

No comments:

Post a Comment