View Single Post
  #1 (permalink)  
Old 09-28-2007, 03:34 PM
FrankyDee FrankyDee is offline
Member
 
Join Date: Jun 2007
Posts: 5
FrankyDee is on a distinguished road
How can I save my XML
Hi there,

I'm a bit of a newbie in Java so please, bare with me.

I have a piece of code that opens an existing XML, adds a node in the 1st element. So far so good. The thing is I didn't find out how to save my XML (I'm pretty sure I'm being dumb here but my boss wants it for yesterday , of course, so here I am).

Here is a sample code I used:
Code:
import java.io.IOException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.sun.org.apache.xerces.internal.parsers.DOMParser; public class Test { private static String sXMLFilename = "C:\\temp\\test.XML"; /** * @param args */ public static void main(String[] args) { // Parse the file DOMParser parser = new DOMParser(); System.out.println("Parsing: " + sXMLFilename); try { parser.parse(sXMLFilename); } catch (SAXException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } // Get the doc System.out.println("\tOK\nGetting the Document object"); Document m_doc = parser.getDocument(); // Get the node System.out.println("\tOK\nGetting NODE_1"); NodeList nodes = m_doc.getElementsByTagName("NODE_1"); // Store it in case we need to create the DRAWbridge node // We assume it exists so no testing here (will be though) Element element = (Element) nodes.item(0); // Check the sub node exists nodes = m_doc.getElementsByTagName("NODE_2"); if (nodes == null || nodes.getLength() == 0) { System.out.println("\tCreating new element"); Element newEl = element.getOwnerDocument().createElement("NODE_2"); System.out.println("\tOK\nAdding to NODE_1"); element.appendChild(newEl); // Now that my new node is insterted, how do I save the XML files ? System.out.println("\tOK\nSaving XML"); } } }
And the XML
Code:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE NODE_1> <NODE_1 />
Thanx in advance for helping

Frank
Reply With Quote
Sponsored Links