0

I'm trying to parse Xml in Blackberry. I copied the xml to the SD card. I tried this code and I succeeded. I tried to insert new tags (Nodes) to the xml and it works but they are added to the end of the file but I don't know if it is the best way to do that, but how can I write the Xml document to the file to save the changes??

 DocumentBuilderFactory docBuilderFactory= DocumentBuilderFactory. newInstance(); 
 DocumentBuilder docBuilder= docBuilderFactory.newDocumentBuilder();
 docBuilder.isValidating();
 doc = docBuilder.parse(conn.openInputStream());
 InsertBlock(doc);
 doc.getDocumentElement ().normalize ();
 NodeList list=doc.getElementsByTagName("*");
 node=new String();
 element = new String();

 for (int i=0;i<list.getLength();i++){
      Node value=list.item(i).getChildNodes().item(0);
      node=list.item(i).getNodeName();
      element=value.getNodeValue();
 }

And for inserting new Nodes :

Node emp=myDocument.createElement("Emp");
Text NodeText = myDocument.createTextNode("DD");
emp.appendChild(NodeText);
myDocument.appendChild(emp);
RAS
  • 8,100
  • 16
  • 64
  • 86
Reham
  • 1,916
  • 6
  • 21
  • 45

1 Answers1

1

In order to insert new node(s) you should use Node#insertBefore() instead of Node#appendChild(). Check documentation here.

Replace

Node emp=myDocument.createElement("Emp");
Text NodeText = myDocument.createTextNode("DD");
emp.appendChild(NodeText);
myDocument.appendChild(emp); 

with

Node emp=myDocument.createElement("Emp");
Text NodeText = myDocument.createTextNode("DD");
emp.appendChild(NodeText); 
myDocument.insertBefore(emp, someExistingNode); 

Where someExistingNode is the Node (probably Element) before which you want to add your new Node emp.

Edit 1: How to write XML to file

try {
    String filePath = "file:///store/home/user/XmlFile.xml";
    FileConnection fc = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
    if (!fc.exists()) {
        fc.create();  // create the file if it doesn't exist
    } else {
        fc.truncate(0); // truncate the file if it exists
    }

    OutputStream os = fc.openOutputStream();
    XMLWriter xmlWriter = new XMLWriter(os);
    xmlWriter.setPrettyPrint();
    DOMInternalRepresentation.parse(myDocument, xmlWriter);
    os.close();
    fc.close();

} catch (Exception e) {
    // Place exception handling code here
}

Edit 2: Added code sample for node insertion and XML-to-file writing

try {
    // Creating document
    Document myDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

    Element parentElement = myDocument.createElement("parentTag");

    // create first element and append it to parent
    Element firstElement = myDocument.createElement("firstElement");
    firstElement.appendChild(myDocument.createTextNode("1"));
    parentElement.appendChild(firstElement);

    // create third element and append it to parent
    Element thirdElement = myDocument.createElement("thirdElement");
    thirdElement.appendChild(myDocument.createTextNode("3"));
    parentElement.appendChild(thirdElement);

    // create second element and insert it between first and third elements
    Element secondElement = myDocument.createElement("secondElement");
    secondElement.appendChild(myDocument.createTextNode("2"));
    parentElement.insertBefore(secondElement, thirdElement);

    myDocument.appendChild(parentElement);

    // Writing document to file
    String filePath = "file:///store/home/user/XmlFile.xml";
    FileConnection fc = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
    if (!fc.exists()) {
        fc.create();  // create the file if it doesn't exist
    } else {
        fc.truncate(0); // truncate the file if it exists
    }

    OutputStream os = fc.openOutputStream();
    XMLWriter xmlWriter = new XMLWriter(os);
    xmlWriter.setPrettyPrint();
    DOMInternalRepresentation.parse(myDocument, xmlWriter);
    os.close();
    fc.close();            

} catch (ParserConfigurationException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (SAXException e) {
    e.printStackTrace();
}     

Also check this question regarding XML creation on BlackBerry.

Community
  • 1
  • 1
tonymontana
  • 5,728
  • 4
  • 34
  • 53
  • Thank you MrVincenzo..Your answer helped me alot..:) – Reham Feb 18 '12 at 13:53
  • You welcome @Reham. You can delete `Node`s with `Node#removeChild()` method. For example, you can call `parentElement.removeChild(firstElement);` to remove the **firstElement** in my sample code. – tonymontana Feb 18 '12 at 14:44
  • this code works if i create a new node and delete it, but how can i use the remove method if i want to delete an existing node in my xml file? – Reham Feb 19 '12 at 10:12
  • @Reham Parse the XML into a `Document`, find the node you want to remove, remove it with `removeChild()` and write the document back to file again. AFAIK, this is the only way to modify the XML document when using the `Document` class. You can use the `getParentNode()` method to retrieve the node's parent node. – tonymontana Feb 19 '12 at 10:27
  • try{ Node parentElement = myDocument.getParentNode(); Node firstElement = parentElement.getFirstChild(); parentElement.removeChild(firstElement); } catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); i tried this and i'm getting Null Exception } – Reham Feb 19 '12 at 11:13
  • `myDocument.getParentNode()` returns `null`, thus NullPointerException is thrown later. Replace it with `myDocument.getFirstChild()`. – tonymontana Feb 19 '12 at 11:48
  • @MrVincenzo See my ques: http://stackoverflow.com/questions/15361763/read-write-and-create-local-xml-file . i have one xml file which i i have a set to SDCard. i have read this xml successfully. there is no issue upto yet but now i want to add more node in this xml and i want reflect this in my existing xml file. i have tried the below code as per your suggestion http://stackoverflow.com/questions/15361763/read-write-and-create-local-xml-file but getting DOMException . please guide me – Hitarth Mar 14 '13 at 10:09