Better approach for XML Creation in Blackberry

I'm using kXML2 to create/chage/save/read xml. Using it with BlackBerry remember:
- for release you have to preverify it & build proj with ant
Ahmad Ferdous Bin Alam - How to Import kxml jar File to Your Project
Slashdev - BlackBerry Development with Ant & Eclipse
UPDATE: Tutorial: How To Use 3rd Party Libraries in your Applications
- for debug you have to add kXML sources and org.xmlpull.v1 sources to your BB project

Create XML

    Document d = new Document();
    Element root = d.createElement("", "parent");       
    root.setName("catalog");
    Element book = d.createElement("", "child");            
    book.setName("book");       
    book.setAttribute(null, "id", "1");             
    Element author = d.createElement("", "child");              
    author.setName("author");               
    author.addChild(0, Node.TEXT, "Colin Wilson");      
    book.addChild(0, Node.ELEMENT, author);

    Element title = d.createElement("", "child");           
    title.setName("title");             
    title.addChild(0, Node.TEXT, "The Mind Parasites");     
    book.addChild(1, Node.ELEMENT, title);

    Element genre = d.createElement("", "child");           
    genre.setName("genre");
    genre.addChild(0, Node.TEXT, "Horror novel, Science fiction novel");    
    book.addChild(2, Node.ELEMENT, genre);

    Element publishDate = d.createElement("", "child");             
    publishDate.setName("publish-date");                
    publishDate.addChild(0, Node.TEXT, "1967"); 
    book.addChild(3, Node.ELEMENT, publishDate);

    root.addChild(0, Node.ELEMENT, book);
    d.addChild(root.ELEMENT, root);

Save XML on BlackBerry filesystem

  • If use emulator don't forget to emulate SD card (Tools->Change SD Card...)
  • be sure you have access rights for read/write operation

    String fileName = "file:///SDCard/books.xml";
    DataOutputStream os = null;
    FileConnection fc = null;
    try {
        fc = (FileConnection) Connector.open(fileName, Connector.READ_WRITE);
        if (!fc.exists())
            fc.create();
    
        os = fconn.openDataOutputStream();
        KXmlSerializer serializer = new KXmlSerializer();
        serializer.setOutput(os, "UTF-8");
        d.write(serializer);
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    

    See also:
    RIM API - Interface FileConnection
    SUN Dev Network - Getting Started with the FileConnection APIs
    RIM - How To - Add plain text or binary files to an application
    BB Support Forum - Some questions about FileConnection/JSR 75
    Sony Ericsson Forum - Create XML file

Read XML file

    Document d= new Document();
    FileConnection fc =  null;
    DataInputStream is = null;
    try {
        fc = (FileConnection) Connector.open(fileName, Connector.READ);
        is = fc.openDataInputStream();

        KXmlParser parser = new KXmlParser();
        parser.setInput(is, "UTF-8");
        d.parse(parser);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

See also: RoseIndia.net - J2ME Kxml Example

Change XML document

All you have to do is get needed element and change it:

    Element catalog = d.getElement("", "catalog");

    Element book = catalog.getElement("", "book");

    Element title = book.getElement("", "title");
    title.removeChild(0);
    title.addChild(Element.TEXT, "Spider World: The Tower");

    Element publish = book.getElement("", "publish-date");
    publish.removeChild(0);
    publish.addChild(Element.TEXT, "1987");

Output XML document to BlackBerry screen (somewhere in Screen class)

Simply serialize xml doc to string and put it in RichTextField:

    deleteAll();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();       
    KXmlSerializer serializer = new KXmlSerializer();
    try {
        serializer.setOutput(baos, "UTF-8");
        d.write(serializer);    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
    add(new RichTextField(baos.toString()));

What about using the DOMInternalRepresentation class? Despite its name, it's part of the public API and has existed since JDE 4.0.0. Using the DOMInternalReprestationClass you can write the Document to an XMLWriter.

For example, to write to a ByteArrayOutputStream (making it handy to send over a Connection):

ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLWriter xw = new XMLWriter(os);
DOMInternalRepresentation.parse( myDocument, xw );

Naturally, you can use a FileOutputStream to direct the XML output to a file on disc instead of to a byte-array.

(If you can't use external libraries for some reason, this seems like a pretty viable approach)