[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

add a new node to an existing xml file--urgent

Posted on 2006-06-06
11
Medium Priority
?
334 Views
Last Modified: 2010-03-31
public static void write(String out_put_file,String s_comment,String root, String s_id, String infor)
{
//create dom document
Document doc = createDomDocument();
            
//add root
Element element = doc.createElement(root);
doc.appendChild(element);

//add comment at the beginning of the document
 Comment comment = doc.createComment(s_comment);
 element.getParentNode().insertBefore(comment, element);
            
//add nodes to dom file
doc = addNode(doc,element, s_id, infor);
            
        
//write the dom to an xml outFile
writeXmlFile(doc, out_put_file);
}

the method above is used to create a new xml file and add one node, but after xml file is created, I need add a node to this existed xml file, so I need a method like:

void add(String file_name, String comments, String root_name, String id, String infor)
how to do it in java?

thanks
0
Comment
Question by:keepworking
  • 4
  • 2
  • 2
  • +2
11 Comments
 
LVL 10

Accepted Solution

by:
radarsh earned 340 total points
ID: 16845940
Hi keepworking,

1. Read the XML file and construct the DOM tree.
2. Add the node wherever you want as in the example you posted.
3. Transform the document back to file.

________
radarsh
0
 
LVL 10

Assisted Solution

by:radarsh
radarsh earned 340 total points
ID: 16846000
Check http://javaalmanac.com/egs/javax.xml.transform/WriteDom.html for
further help on transforming.

________
radarsh
0
 

Author Comment

by:keepworking
ID: 16846314
thanks radarsh:

Document doc = null;
Element element = null;
if(file_existed==false)
{
doc= createDomDocument();
                                                
element = addRoot("ROOT",doc);
addComment("testing",doc);
file_existed = true;
                                                
}
addNode(doc,element,s_id, infor);

writeXmlFile(doc, "testing.xml");

there is anything wrong, it doesn't work
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:keepworking
ID: 16846338
static Document createDomDocument()
      {
            try
            {
                  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                  Document doc = builder.newDocument();
                  return doc;
            }
            catch (ParserConfigurationException e)
            {
          }
          return null;
      }

      public static Element addRoot (String s_root, Document doc)
      {
            try
            {
                  Element element = doc.createElement(s_root);
                  doc.appendChild(element);
                  return element;
            }
            catch (DOMException e)
            {
            }
            
            return null;
        
      }
      
//add comment to dom
      public static void addComment (String s_comment, Document doc)
      {
            //add comment at the beginning of the document
            Element element = doc.getDocumentElement();
          Comment comment = doc.createComment(s_comment);
          element.getParentNode().insertBefore(comment, element);
      }
      

      public static Document addNode(Document doc, Element element, String s_id, String infor)      
      {
            try
            {
                  
                  // Insert the Record element node
                Element element_Record = doc.createElement("RECORD");
                element.appendChild(element_Record);

                Element element_ID = doc.createElement("ID");
                element_Record.appendChild(element_ID);
                  
                Element element_String = doc.createElement("INFORMATION");
                element_Record.appendChild(element_String);
                  
                element_ID.appendChild(doc.createTextNode(s_id));
                element_String.appendChild(doc.createTextNode(infor));
               
            }
            catch (DOMException e){
            }
            
            return doc;
            
      }

0
 
LVL 10

Assisted Solution

by:mukundha_expert
mukundha_expert earned 300 total points
ID: 16846780
Hi ,

Hope this might help u. this method will get the input fileName( XML file) and the nodename and value to be inserted.

i have inserted the node in the root node itself.
to insert the new node in your desired location parse through the root element and find the node where u want to insert and append the created child. it will again overwrite the file given as input to the new XML.      


public void writeToXml ( String fileName, String insertNode, String insertValue ) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError
      {
            FileReader file =   new FileReader ( fileName )  ;
            InputSource source = new InputSource ( file );
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
            
            DocumentBuilder builder = factory.newDocumentBuilder() ;
            Document doc = builder.parse ( source ) ;
            // this is the root node for the document
            Element root = doc.getDocumentElement() ;
            
            // Create the Node you want,
            // parse the root node to get to the node where you want to insert it
            // here am inserting at the root node
            
            Node newNode = doc.createElement( insertNode) ;
            Node test = doc.createTextNode ( insertValue ) ;
            test.setNodeValue( insertValue ) ;
            //adding to root node
            root.appendChild (newNode) ;
            newNode.appendChild(test);
            
            file.close() ;
            
            FileWriter writeFile = new FileWriter ( fileName );
            BufferedWriter writer = new BufferedWriter (writeFile);

            StringWriter out = new StringWriter ();
TransformerFactory.newInstance().newTransformer().transform ( new DOMSource ( root) , new StreamResult ( out ));

            writer.write( out.toString () ) ;
            writer.flush () ;
      }


cheers,
Mukundh
0
 

Author Comment

by:keepworking
ID: 16848036
Mukundh:

" it will again overwrite the file given as input to the new XML. " means by your method, you will get a new xml file everytime, right?

what I need is:

there is a xml file, with one node, I need add one more node to this xml file, your method can do that?

thanks
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 60 total points
ID: 16849716
>> " it will again overwrite the file given as input to the new XML. " means by your method, you will get a new xml file everytime, right?

No, it will over-write the initial file.
0
 
LVL 12

Assisted Solution

by:Giant2
Giant2 earned 300 total points
ID: 16849871
After creating your Dom (as radarsh initial suggest) you can save it in this manner:
(String fileName is the name of the file you are saving and doc is the DOM Document object you have)
            try{
            File outFile=new File(fileName);
            FileWriter out=new FileWriter(outFile);
            save(doc,out);
            out.close();
            }catch (IOException ex){System.out.println("Error saving "+fileName);}


      private void save(Node n,FileWriter out) throws IOException{
            NodeList lista=n.getChildNodes();
            for (int i=0;i<lista.getLength();i++){
                  Node child=lista.item(i);
                  if (!child.getNodeName().equals("#text")){//if you need to remove text
                        if (child.getNodeName().equals("#comment")){
                              //System.out.println("<!-- "+child.getNodeValue()+" -->");
                              out.write("<!-- "+child.getNodeValue()+" -->\n");
                              }
                        else {
                              //System.out.println(child);
                              out.write(child.toString()+"\n");
                        }
                  }//end if #text
            }//end for i
      }

Hope this could help you.
Bye, Giant.
0
 
LVL 10

Assisted Solution

by:mukundha_expert
mukundha_expert earned 300 total points
ID: 16851296
>> "there is a xml file, with one node, I need add one more node to this xml file, "

ya it will do . it will overwrite only the original file with the new XML
0
 

Author Comment

by:keepworking
ID: 16857041
ok, I finished code, maybe my question is not clear.

thanks
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16858614
Which code did you use? Why the C grade?
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month18 days, 12 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question